在VBA中經(jīng)常要用到文件對話框來進(jìn)行打開文件、選擇文件或選擇文件夾的操作。
用Microsoft Office提供的文件對話框比較方便。
用法如下
Application.FileDialog(fileDialogType)
fileDialogType
MsoFileDialogType 類型,必需。文件對話框的類型。
|
MsoFileDialogType 可為以下 MsoFileDialogType 常量之一。 |
|
msoFileDialogFilePicker 允許用戶選擇文件。 |
|
msoFileDialogFolderPicker 允許用戶選擇一個文件夾。 |
|
msoFileDialogOpen 允許用戶打開文件。用Excel打開。 |
|
msoFileDialogSaveAs 允許用戶保存一個文件。 |
分別舉例如下:
1、msoFileDialogFilePicker
1)選擇單個文件
復(fù)制內(nèi)容到剪貼板
代碼:
Sub SelectFile()
'選擇單一文件
'www.
With
Application.FileDialog(msoFileDialogFilePicker)
.AllowMultiSelect
= False
'單選擇
.Filters.Clear
'清除文件過濾器
.Filters.Add
"Excel Files", "*.xls;*.xlw"
.Filters.Add
"All Files", "*.*"
'設(shè)置兩個文件過濾器
If .Show = -1
Then
'FileDialog 對象的
Show 方法顯示對話框,并且返回 -1(如果您按 OK)和 0(如果您按 Cancel)。
MsgBox
"您選擇的文件是:" & .SelectedItems(1), vbOKOnly +
vbInformation, "智能Excel"
End
If
End With
End Sub
2)選擇多個文件
復(fù)制內(nèi)容到剪貼板
代碼:
Sub
SelectFile()
'選擇多個文件
'www.
Dim l As Long
With
Application.FileDialog(msoFileDialogFilePicker)
.AllowMultiSelect
= True
'單選擇
.Filters.Clear
'清除文件過濾器
.Filters.Add
"Excel Files", "*.xls;*.xlw"
.Filters.Add
"All Files", "*.*"
'設(shè)置兩個文件過濾器
.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
復(fù)制內(nèi)容到剪貼板
代碼:
Sub
SelectFolder()
'選擇單一文件
'www.
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方法來實際打開或者保存文件。
|