为了使VBA程序编写的小工具更加灵活,有时候需要我们像WORD或EXCEL一样,弹出一个对话让用户去选择需要的文件或文件夹。
在VBA中,FileDialog对象提供了一个文件对话框的功能。它也WORD、EXCEL、POWERPOINT中标准的打开、保存、另存为等对话框类似。可以让我们实现一些很灵活的功能。
FileDialog对象有四种类型:
打开对话框;
另存为对话框;
文件选取器对话框;
文件夹选取器对话框;
FileDialog对象在使用前,必须先通过Application.FileDialog方法获取一个对象,然后设置该对象的属性,最后使用SHOW方法显示对话框。
下面我们通过几个例子,来看一下FileDialog对象如何使用。
1、通过单选对话框,选择单个文件
Sub 按钮1_Click()
'这是一个选择单个文件对话框的例子
'Mac私塾出品:macsishu.com
With Application.FileDialog(msoFileDialogFilePicker)
.AllowMultiSelect = False
.Filters.Clear
.Filters.Add "Excel Files", "*.xls,*.xlsx"
.Filters.Add "All Files", "*.*"
If .Show = -1 Then
MsgBox "选择的文件路径为:" + .SelectedItems(1), vbOKOnly + vbInformation, "Mac私塾:macsishu.com"
End If
End With
End Sub
2、通过多选对话框,选择多个文件
Sub 按钮2_Click()
'这是一个选择多个文件对话框的例子
'Mac私塾出品:macsishu.com
Dim sctItem As Variant
With Application.FileDialog(msoFileDialogFilePicker)
.AllowMultiSelect = True '把这里的False改为True即可支持文件多选
.Filters.Clear
.Filters.Add "Excel Files", "*.xls,*.xlsx"
.Filters.Add "All Files", "*.*"
If .Show = -1 Then
MsgBox "选择了 " + CStr(.SelectedItems.Count()) + " 个文件。"
For Each sctItem In .SelectedItems
MsgBox "选择的文件路径为:" + sctItem, vbOKOnly + vbInformation, "Mac私塾:macsishu.com"
Next
End If
End With
End Sub
3、通过文件夹对话框,选择单个文件夹
Sub 按钮3_Click()
'这是一个选择文件夹的例子
'Mac私塾出品:macsishu.com
With Application.FileDialog(msoFileDialogFolderPicker)
If .Show = -1 Then
MsgBox "选择的文件夹为:" + .SelectedItems(1), vbOKOnly + vbInformation, "Mac私塾:macsishu.com"
End If
End With
End Sub

