|
本帖最后由 秋意正浓 于 2012-9-5 16:56 编辑
Set fdg = Application.FileDialog(msoFileDialogOpen) '表示文件对话框的实例。
With fdg
.Filters.Clear '清除filter,注意顺序
.Filters.Add "EXCEL2003(*.XLS)", "*.xls" '设置过滤器
.Filters.Add "所有文件(*.*)", "*.*" '设置过滤器
.InitialFileName = ThisWorkbook.Path '设置默认文件夹
.AllowMultiSelect = False
.Show
For lngCount = 1 To .SelectedItems.Count '循环所有选中的文件
wbname = .SelectedItems(lngCount) '打开所有选中的文件
Workbooks.Open filename:=wbname
Next lngCount
End With
以上代码是选择打开指定文件的代码,但是,当我点弹出来的对话框的“取消”键时,提示代码错误,如何避免这个错误?
对FILEDIALOG的返回参数要做判断。
FileDialog.Show 方法显示文件对话框并返回一个 Long 类型的值,指示用户按下的是“操作”按钮 (-1) 还是“取消”按钮 (0)。 你对SHOW的返回值要做判断才行。 - Sub Main()
- 'Declare a variable as a FileDialog object.
- Dim fd As FileDialog
- 'Create a FileDialog object as a File Picker dialog box.
- Set fd = Application.FileDialog(msoFileDialogFilePicker)
- 'Declare a variable to contain the path
- 'of each selected item. Even though the path is aString,
- 'the variable must be a Variant because For Each...Next
- 'routines only work with Variants and Objects.
- Dim vrtSelectedItem As Variant
- 'Use a With...End With block to reference the FileDialog object.
- With fd
- 'Use the Show method to display the File Picker dialog box and return the user's action.
- 'The user pressed the button.
- If .Show = -1 Then
- 'Step through each string in the FileDialogSelectedItems collection.
- For Each vrtSelectedItem In .SelectedItems
- 'vrtSelectedItem is a string that contains the path of each selected item.
- 'You can use any file I/O functions that you want to work with this path.
- 'This example displays the path in a message box.
- MsgBox "The path is: " & vrtSelectedItem
- Next vrtSelectedItem
- 'The user pressed Cancel.
- Else
- End If
- End With
- 'Set the object variable to nothing.
- Set fd = Nothing
复制代码
|
|