VBA 打开 Excel 文件 - 对话框更改

标签 vba excel

我正在运行一个 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/

相关文章:

arrays - Excel:将数组传递给用户定义函数 (VBA)

excel - 在Excel宏中选择范围

excel - 如何使用vba在单元格中输入公式

vba - Excel 宏将数据插入下一行

excel - 如何将宏引用到当前工作表中的单元格范围?

vba - "index into the specified collection is out of bounds"不同系统不一致

svn - 存储库信息 (SVN) 与 Excel 集成

excel - 锁定某些单元格中的编辑,但没有进一步的保护

linux - 为什么 Linux "sort -u"比 Excel 快这么多

Excel如何用文本填充所有选定的空白单元格