[VB6]使用File Dialog選擇檔案


加入Common Dialog的控件, 成功加入後出現紅框的Icon表示成功
Microsoft Common Dialog Control 6.0

Control Object of Form
先在Form上建立CommonDialog的控件, 如未建立使用控件會跳出Variable not defined.

Button呼叫CommonDialog, 顯示FileDialog


Private Sub CTL_BTN_SEL_FILE_Click()
    With CommonDialog1
        .DialogTitle = "Select the Report File"
        .Filter = "Custom Format (*.xls)|*.xls"
        .Flags = .Flags + cdlOFNHideReadOnly
        .InitDir = specialPath("Desktop")
        .ShowOpen

        CTL_BTN_SEL_FILE.Caption = .fileName
    End With
End Sub

  • Property DialogTitle As String
設定DialogTitle

  • Property Filter As String
設定檔案類型

  • Property Flags As Long
設定屬性

  • Property InitDir As String
設定初始位置

  • Sub ShowOpen()
顯示File Dialog畫面

  • Property FileName As String
取得選擇的File Path & Name


- 偵測是否有選取檔案
在開啟File Dialog按下取消按鈕, FileName回傳為Null String, 如再打開該路徑檔案即發生錯誤, 因為Null String.
解法可檢查FileName路徑是否存在, 之後再打開路徑檔案.
以下解法則在File Dialog判斷是否為Null String, 可省略路徑檢查的程序.

  • Property CancelError As Boolean
可將CancelError設為True, 在按下取消按鈕時產生Error Event, 即如下錯誤訊息

搭配On Error GoTo即可判斷是否為按下取消按鈕
Private Sub CTL_BTN_SEL_FILE_Click()
    On Error GoTo ERROR_HANDLER


    With CommonDialog1
        .CancelError = True ' for cancel button
        .DialogTitle = "Select the Report File"
        .Filter = "UltraChip Report (*.xls)|*.xls"
        .Flags = .Flags + cdlOFNHideReadOnly
        .InitDir = specialPath("Desktop")
        .ShowOpen

        CTL_BTN_SEL_FILE.Caption = .fileName
    End With

    Exit Sub


ERROR_HANDLER:
    debugMsg (Err.Number & vbTab & Err.Description) ‘ cancel button

End Sub


Ref

留言

這個網誌中的熱門文章

Download Visual Studio Community 2015 update 3 ISO-FIle