我相信我已经创建了一个可能复制用户 @Alain 的自定义函数的函数,FindConstants("Message Here")
. 让 VBA 调用目录路径的技巧是通过 Windows API 运行。该函数调用文件 DLL 来拉出目录浏览器。然后它将选择保存到DirPath()
. 我不确定如何在 64 位机器上调用这些声明,这是假设您运行的是 Windows 7。这是我目前所拥有的:
Option Explicit
Public Type BROWSEINFO
hOwner As Long
pidlRoot As Long
pszDisplayName As String
lpszTitle As String
ulFlags As Long
lpfn As Long
lParam As Long
iImage As Long
End Type
'32-bit API declarations
Declare Function SHGetPathFromIDList Lib "shell32.dll" _
Alias "SHGetPathFromIDListA" (ByVal pidl As Long, ByVal pszPath As String) _
As Long
Declare Function SHBrowseForFolder Lib "shell32.dll" _
Alias "SHBrowseForFolderA" (lpBrowseInfo As BROWSEINFO) As Long
Function DirPath(Optional Msg) As String
Dim bInfo As BROWSEINFO
Dim path As String
Dim r As Long, x As Long, pos As Integer
bInfo.pidlRoot = 0&
' Window title information
If IsMissing(Msg) Then
bInfo.lpszTitle = "Select a folder."
Else
bInfo.lpszTitle = Msg
End If
' Directory information to return
bInfo.ulFlags = &H1
' Display the browsing dialog
x = SHBrowseForFolder(bInfo)
' Parse
path = Space$(512)
r = SHGetPathFromIDList(ByVal x, ByVal path)
If r Then
pos = InStr(path, Chr$(0))
DirPath = Left(path, pos - 1)
Else
DirPath = "" ' Saves no directory if nothing is selected!
End If
End Function
这是一个用于测试上述功能的 Sub:
Sub Test()
Dim Msg As String
Msg = "Please select a template repository."
MsgBox GetDirectory(Msg)
End Sub
抱歉,这有点乱,我不知道如何使用 Markdown 清理代码块……这不是一个完整的答案,我花了一段时间才知道,因为我不熟悉通过 API 调用。另外,MSDN 是为 C+ 编写的,我不知道,所以我必须找到一些将 C+ 声明等同于 VBA 声明的表格资源(As Long 与 *FAR 等)。如果有人可以贡献或识别他们在 Alain 的代码中发现的功能作为附加组件或众所周知的 UDF,我将保持这个问题的开放性。当我创建和学习时,我会更多地编辑这个答案。