我正在运行一个 Excel VBA 脚本,其中我试图打开一个对话框来选择一个 Excel 文件并打开该 Excel 文件。我尝试给出文件夹的路径,以便最终用户可以直接进入该文件夹并选择他想要的文件。
但是,它第一次工作正常,但下次运行时,它会打开最终用户上次选择文件的文件夹。
这是我的代码,
thisYear = Year(Date)
'change the display name of the open file dialog
Application.FileDialog(msoFileDialogOpen).Title = _
"Select Input Report"
'Remove all other filters
Application.FileDialog(msoFileDialogOpen).Filters.Clear
'Add a custom filter
Call Application.FileDialog(msoFileDialogOpen).Filters.Add( _
"Excel Files Only", "*.xls*")
'Select the start folder
Application.FileDialog(msoFileDialogOpen _
).InitialFileName = "\\driveA\Reports\" & thisYear & ""
file = Application.FileDialog(msoFileDialogOpen).Show
Application.FileDialog(msoFileDialogOpen).Execute
如何解决这个问题?
最佳答案
最好使用对象变量,而不是重复调用 Application.FileDialog
,因为每次调用 Application.FileDialog
都可能被视为该类的新实例,这可能解释了您的问题。这是一个我还没有测试过的假设,我也不是 100%,但它似乎是合理的。
尝试一下:
Dim fdlg as FileDialog
Set fdlg = Application.FileDialog(msoFileDialogOpen)
'change the display name of the open file dialog
fdlg.Title = "Select Input Report"
'Remove all other filters
fdlg.Filters.Clear
'Add a custom filter
fdlg.Filters.Add "Excel Files Only", "*.xls*"
'Select the start folder
fdlg.InitialFileName = "\\driveA\Reports\" & thisYear & ""
'Display to user:
fdlg.Show
'Ensure selection:
If fdlg.SelectedItems.Count <> 0 Then
'Captures the filename chosen:
file = fdlg.SelectedItems(1)
'Then, you probably want to open it:
Set wb = Workbooks.Open(file)
Else
'no file is selected, add error-handling or inform user, exit sub early, etc.
End If
关于VBA 打开 Excel 文件 - 对话框更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43622367/