以前自己写的一套VB编程基础系列教程,适合VB初学者。

CommonDialog.ShowOpen可以选择一个文件,但是选定一个文件夹时是默认打开这个文件夹,我现在想只定位到文件夹该怎么办呢?
添加一个Text、Command和Commondialog控件。

VB选择、定位文件夹程序代码如下:

Option Explicit
Private Declare Function SHBrowseForFolder Lib "shell32.dll" Alias _
"SHBrowseForFolderA" (LpBrowseInfo As BROWSEINFO) As Long
Private Declare Function SHGetPathFromIDlist Lib "shell32.dll" Alias _
"SHGetPathFromIDListA" (ByVal pidl As Long, ByVal pszPath As String) As Long
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

Private Function GetFolder(ByVal hWnd As Long, Optional Title As String) As String
Dim bi As BROWSEINFO
Dim pidl As Long
Dim folder As String
folder = Space(255)
With bi
If IsNumeric(hWnd) Then .hOwner = hWnd
.pidlroot = 0
If Title <> "" Then
.lpszTitle = Title & Chr$(0)
Else
.lpszTitle = "选择目录" & Chr$(0)
End If
End With

pidl = SHBrowseForFolder(bi)
If SHGetPathFromIDlist(ByVal pidl, ByVal folder) Then
GetFolder = Left(folder, InStr(folder, Chr$(0)) - 1)
Else
GetFolder = ""
End If
End Function

Private Sub Command1_Click()
Text1.Text = GetFolder(Me.hWnd, "请选择一个文件夹:")
End Sub

如何添加Commondialog控件?

可能有的小菜会找不到,这里说明一下。在VB环境里按Ctrl+T,在弹出的“部件”里选择Microsoft Common Dialog Control 6.0,然后“确定”即可。