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

VBA打开Excel文件-对话框更改,vba,excel,Vba,Excel,我正在运行一个excel vba脚本,在该脚本中,我试图打开一个对话框来选择一个excel文件并打开该excel文件。我尝试给出文件夹的路径,以便最终用户可以直接转到该文件夹并选择他想要的文件 但是,它第一次工作正常,但下次运行时会打开最终用户上次选择文件的文件夹 这是我的密码 thisYear = Year(Date) 'change the display name of the open file dialog Application.FileDialog(msoFileDia

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

如何解决此问题?

最好使用对象变量,而不是重复调用
应用程序.FileDialog
,因为每次调用
应用程序.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
Dim fdlg as FileDialog
设置fdlg=Application.FileDialog(msoFileDialogOpen)
'更改“打开文件”对话框的显示名称
fdlg.Title=“选择输入报告”
'删除所有其他筛选器
fdlg.Filters.Clear
'添加自定义筛选器
fdlg.Filters.Add“仅限Excel文件”,“*.xls*”
'选择开始文件夹
fdlg.InitialFileName=“\\driva\Reports\”&今年&“
'向用户显示:
秀
“确保选择:
如果fdlg.SelectedItems.Count为0,则
'捕获所选的文件名:
file=fdlg.SelectedItems(1)
'然后,您可能要打开它:
设置wb=工作簿。打开(文件)
其他的
'未选择任何文件,添加错误处理或通知用户,提前退出sub等。
如果结束

根据,您需要使用.show来显示对话框,如果您使用的是msoFileDialogOpen,则应使用.execute来打开文件。也许这可以解释你的问题。@RichHolton谢谢先生:)@RichHolton我已经更新了我的代码。你能告诉我哪里出了问题吗?还是不行?我会再搔搔头…@RichHolton Ya,谢谢,如果我找到任何答案,我也会更新。你的代码对我很有用。我的意思是,当我第一次运行宏时,它会选择代码中提到的路径并进入特定文件夹。让我们将此文件夹称为文件夹A。在文件夹A中,用户有三个文件夹:文件夹1、文件夹2和文件夹3。如果用户从文件夹2中拾取文件,那么下次运行此宏时。它直接将最终用户带到文件夹2,而不是文件夹A,并允许他选择所需的文件夹。好的,谢谢您的澄清。这听起来确实很奇怪和出乎意料!没问题,谢谢:)