本帖最后由 Francis 于 2014-11-17 09:50 编辑
回想一下,可能阿丹對6樓那個對話框依然感興趣,就繼續說說吧。
由於SW-API沒有提供『選取資料夾對話框』的函數,那就需要用到 Windows-API 其中的 shell32.dll 來實現,
做法是,在宏內再加多一個模組(模塊),加入以下語句:
- Private Const BIF_RETURNONLYFSDIRS As LongPtr = &H1
- Private Const BIF_DONTGOBELOWDOMAIN As LongPtr = &H2
- Private Const BIF_RETURNFSANCESTORS As LongPtr = &H8
- Private Const BIF_BROWSEFORCOMPUTER As LongPtr = &H1000
- Private Const BIF_BROWSEFORPRINTER As LongPtr = &H2000
- Private Const BIF_BROWSEINCLUDEFILES As LongPtr = &H4000
- Private Const MAX_PATH As Long = 260
-
- Type BrowseInfo
- hOwner As LongPtr
- pidlRoot As LongPtr
- pszDisplayName As String
- lpszINSTRUCTIONS As String
- ulFlags As LongPtr
- lpfn As LongPtr
- lParam As LongPtr
- iImage As LongPtr
- End Type
-
- Type SHFILEOPSTRUCT
- hwnd As LongPtr
- wFunc As LongPtr
- pFrom As String
- pTo As String
- fFlags As Integer
- fAnyOperationsAborted As Boolean
- hNameMappings As LongPtr
- lpszProgressTitle As String
- End Type
-
- Declare PtrSafe Function SHBrowseForFolderA Lib "shell32.dll" _
- (lpBrowseInfo As BrowseInfo) As LongPtr
-
- Declare PtrSafe Function SHGetPathFromIDListA Lib "shell32.dll" _
- (ByVal pidl As LongPtr, ByVal pszPath As String) As Boolean
-
- Function BrowseFolder(Optional Caption As String = "") As String
-
- Dim BrowseInfo As BrowseInfo
- Dim FolderName As String
- Dim ID As LongPtr
- Dim Res As Boolean
-
- With BrowseInfo
- .hOwner = 0
- .pidlRoot = 0
- .pszDisplayName = String$(MAX_PATH, vbNullChar)
- .lpszINSTRUCTIONS = Caption
- .ulFlags = &H1
- .lpfn = 0
- End With
- FolderName = String$(MAX_PATH, vbNullChar)
- ID = SHBrowseForFolderA(BrowseInfo)
- If ID Then
- Res = SHGetPathFromIDListA(ID, FolderName)
- If Res Then
- BrowseFolder = Left$(FolderName, InStr(FolderName, _
- vbNullChar) - 1)
- End If
- End If
-
- End Function
复制代码 這就可以生成了自己的『選取資料夾對話框』的函數:BrowseFolder 了。
再回到自訂表單(用戶窗體)見5樓,建立多一個按鈕,
雙擊新增的按鈕,貼上以下代碼:
- Private Sub CommandButton2_Click()
- myPath = BrowseFolder("TEST")
- TextBox1 = TextBox1 & myPath & Chr(13)
- End Sub
复制代码 需注意,宏程序的名稱 必須與 按鈕的名稱“CommandButton?”一致。
修改2個按鈕的Caption,可讓用起來更便利,
例如:按鈕 CommandButton1的Caption叫做『處理資料夾內所有零件的瑣事』及 按鈕 CommandButton2的Caption叫做『選取資料夾』。
注意:由於這個做法存在3個致命弱點:
1. 在某情況有衝碼現象。
2. 瀏覽資料夾不能設定默認路徑,及不會記憶之前的路徑位置,導致每次都要從『我的電腦』點選下去,非常繁瑣。
3. 資料夾內不一定所有零件檔案都需要處理瑣事的,執行前要把例外檔案移開,非常不便。
加上採用Excel作為界面的課題已經開展,感到這課題繼續下去的意義不大,
但又顧慮到做事需有始有終,故此作出上述說明。
如各位有興趣,是可繼續討論這課題下去的。
|