首页 文章

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

提问于
浏览
2

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

如何解决这个问题?

2 回答

  • 0

    最好使用对象变量而不是重复调用 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
    
  • 2

    在调用对话框之前添加它:

    ChDir "\\path\to\my\desired\folder\"

    然后使用 CurDir() 而不是文件夹的显式路径 .

    如果您还需要更换驱动器,请使用:

    ChDrive "X"

    另请阅读here .

相关问题