Using a Windows API function to select a directory

In this section, I present a function named GetDirectory that displays the dialog box shown in Figure 12-9 and returns a string that represents the selected directory. If the user clicks Cancel, the function returns an empty string.

Browse for Folder

Please select a location for the backup, j My Documents + Cyberlink

MS Honey My Data Sources

^My Music My Pictures My Videos ft Pj) My Weblog Posts i± jfcl My Webs Q Photoshop

OK Cancel

Figure 12-9: Use an API function to display this dialog box.

The GetDirectory function takes one argument, which is optional. This argument is a string that will be displayed in the dialog box. If the argument is omitted, the dialog box displays Select a folder as the message.

Following are the API declarations required at the beginning of the workbook module. This function also uses a custom data type, called browseinfo.

'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

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

The GetDirectory function follows:

Function GetDirectory(Optional Msg) As String Dim bInfo As BROWSEINFO Dim path As String

Dim r As Long, x As Long, pos As Integer

' Root folder = Desktop bInfo.pidlRoot = 0&

' Title in the dialog

If IsMissing(Msg) Then bInfo.lpszTitle = "Select a folder."

Else bInfo.lpszTitle = Msg End If

' Type of directory to return bInfo.ulFlags = &H1

' Display the dialog x = SHBrowseForFolder(bInfo)

' Parse the result path = Space$(512)

r = SHGetPathFromIDList(ByVal x, ByVal path) If r Then pos = InStr(path, Chr$(0)) GetDirectory = Left(path, pos - 1)

Else

GetDirectory = "" End If End Function

The simple procedure that follows demonstrates how to use the GetDirectory function in your code. Executing this procedure displays the dialog box. When the user clicks OK, the MsgBox function displays the full path of the selected directory. If the user clicks Cancel, the message box displays Canceled.

Sub GetAFolderl()

Dim Msg As String Dim UserFile As String

Msg = "Please select a location for the backup." UserFile = GetDirectory(Msg) If UserFile = "" Then MsgBox "Canceled"

Else

MsgBox UserFile End If End Sub

Note Unfortunately, there is no easy way to specify a default or starting directory.

0 0

Post a comment