在本文中,我们创建了用于显示对话框的过程,该过程用于浏览文件夹以选择文件夹。

此代码可与其他需要在运行时选择文件夹的宏一起使用。

SelectingFolder

逻辑解释

在本文中,我们引用了两个API函数来显示用于浏览文件夹的对话框。

当我们使用文件夹浏览器选择任何特定的文件夹时,对话框将返回所选文件夹的路径。

请遵循以下代码

Option Explicit

'Declaring user data type

'Used by the function GetFolderName

Private 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

'Declaring reference to API Function

Private Declare Function SHGetPathFromIDList Lib "shell32.dll" _

Alias "SHGetPathFromIDListA" (ByVal pidl As Long, ByVal pszPath As String) As Long

Private Declare Function SHBrowseForFolder Lib "shell32.dll" _

Alias "SHBrowseForFolderA" (lpBrowseInfo As BROWSEINFO) As Long

Function GetFolderName(Msg As String) As String

'Returns the name of the folder selected by the user

Dim bInfo As BROWSEINFO, path As String, r As Long

Dim X As Long, pos As Integer



bInfo.pidlRoot = 0

'Type of directory to return

bInfo.ulFlags = &H1

'Display the dialog

X = SHBrowseForFolder(bInfo)

'Parse the result

path = Space$(512)

'Calling API function

r = SHGetPathFromIDList(ByVal X, ByVal path)

'Code for deleting extra spaces in the end of folder name return

If r Then

pos = InStr(path, Chr(0))

GetFolderName = Left(path, pos - 1)

Else

GetFolderName = ""

End If

End Function

Sub TestGetFolderName()

Dim FolderName As String

'Calling function GetFolderName

FolderName = GetFolderName("Select a folder")

If FolderName = "" Then

MsgBox "You didn't select a folder."

Else

MsgBox "You selected this folder: " & FolderName

End If

End Sub

如果您喜欢此博客,请在Facebook和Facebook上与您的朋友分享。

我们希望收到您的来信,请让我们知道如何改善我们的工作并为您做得更好。写信给我们[email protected]