我正在运行一个 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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句