[VB6]使用File Dialog選擇檔案


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

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

Button呼叫CommonDialog, 顯示FileDialog


  1. Private Sub CTL_BTN_SEL_FILE_Click()
  2. With CommonDialog1
  3. .DialogTitle = "Select the Report File"
  4. .Filter = "Custom Format (*.xls)|*.xls"
  5. .Flags = .Flags + cdlOFNHideReadOnly
  6. .InitDir = specialPath("Desktop")
  7. .ShowOpen
  8. CTL_BTN_SEL_FILE.Caption = .fileName
  9. End With
  10. 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即可判斷是否為按下取消按鈕
  1. Private Sub CTL_BTN_SEL_FILE_Click()
  2. On Error GoTo ERROR_HANDLER
  3.  
  4.  
  5. With CommonDialog1
  6. .CancelError = True ' for cancel button
  7. .DialogTitle = "Select the Report File"
  8. .Filter = "UltraChip Report (*.xls)|*.xls"
  9. .Flags = .Flags + cdlOFNHideReadOnly
  10. .InitDir = specialPath("Desktop")
  11. .ShowOpen
  12.  
  13. CTL_BTN_SEL_FILE.Caption = .fileName
  14. End With
  15.  
  16. Exit Sub
  17.  
  18.  
  19. ERROR_HANDLER:
  20. debugMsg (Err.Number & vbTab & Err.Description) ‘ cancel button
  21.  
  22. End Sub


Ref

留言

這個網誌中的熱門文章

[VB6]MSFlexGrid使用記錄

[VBA]如何藉由使用 Excel 中的 Visual Basic 程序選取儲存格/範圍