在VBA中经常要用到文件对话框来进行打开文件、选择文件或选择文件夹的操作。
用Microsoft Office提供的文件对话框比较方便。
用法如下
Application.FileDialog(fileDialogType)
fileDialogType MsoFileDialogType 类型,必需。文件对话框的类型。
MsoFileDialogType 可为以下 MsoFileDialogType 常量之一。 |
msoFileDialogFilePicker 允许用户选择文件。 |
msoFileDialogFolderPicker 允许用户选择一个文件夹。 |
msoFileDialogOpen 允许用户打开文件。用Excel打开。 |
msoFileDialogSaveAs 允许用户保存一个文件。 |
分别举例如下:
1、msoFileDialogFilePicker
1)选择单个文件
Sub SelectFile() '选择单一文件 With Application.FileDialog(msoFileDialogFilePicker) .AllowMultiSelect = False '单选择 .Filters.Clear '清除文件过滤器 .Filters.Add "Excel Files", "*.xls;*.xlw" .Filters.Add "All Files", "*.*" '设置两个文件过滤器 If .Show = -1 Then 'FileDialog 对象的 Show 方法显示对话框,并且返回 -1(如果您按 OK)和 0(如果您按 Cancel)。 MsgBox "您选择的文件是:" & .SelectedItems(1), vbOKOnly + vbInformation, "智能Excel" End If End With End Sub
2)选择多个文件
Sub SelectFile() '选择多个文件 Dim l As Long With Application.FileDialog(msoFileDialogFilePicker) .AllowMultiSelect = True '单选择 .Filters.Clear '清除文件过滤器 .Filters.Add "Excel Files", "*.xls;*.xlw" .Filters.Add "All Files", "*.*" '设置两个文件过滤器 .Show 'FileDialog 对象的 Show 方法显示对话框,并且返回 -1(如果您按 OK)和 0(如果您按 Cancel)。 For l = 1 To .SelectedItems.Count MsgBox "您选择的文件是:" & .SelectedItems(l), vbOKOnly + vbInformation, "智能Excel" Next End With End Sub
2、msoFileDialogFolderPicker
文件夹仅能选择一个
Sub SelectFolder() '选择单一文件 With Application.FileDialog(msoFileDialogFolderPicker) If .Show = -1 Then 'FileDialog 对象的 Show 方法显示对话框,并且返回 -1(如果您按 OK)和 0(如果您按 Cancel)。 MsgBox "您选择的文件夹是:" & .SelectedItems(1), vbOKOnly + vbInformation, "智能Excel" End If End With End Sub
3、msoFileDialogOpen
4、msoFileDialogSaveAs
使用方法与前两种相同
只是在.show可以用.Execute方法来实际打开或者保存文件。
例如:
Sub SelectFile() '选择单一文件 With Application.FileDialog(msoFileDialogFilePicker) .AllowMultiSelect = False '单选择 .Filters.Clear '清除文件过滤器 .Filters.Add "Excel Files", "*.xls;*.xlw" .Filters.Add "All Files", "*.*" '设置两个文件过滤器 .Execute End With End Sub
另见:
http://justsee.iteye.com/blog/1468743
转自因特网,感谢因特网的雷锋们!