You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VBA FileDialog如何筛选含Orders/Registrations的两类Excel文件?

解决VBA FileDialog同时筛选两类文件名的问题

你用InitialFileName = "*Orders*|*Registrations*"无效的原因很明确:InitialFileName属性不支持用|分隔多个文件名通配符,这个属性仅用来指定默认打开的路径,或者单个文件名模板,多类型/多文件名的筛选必须通过FileDialog.Filters来实现。

修改方案

核心是通过.Filters.Add添加包含双通配符的筛选规则,多个通配符用分号;分隔。下面是修改后的完整代码,标注了关键修改点:

Function getFiles(Optional nameFilter As String = "", Optional windowTitle As String = "", Optional multiSelect As Boolean = True, Optional maxSelected As Integer = 10000) As FileDialogSelectedItems
' Prompts the user to choose one or more files and returns the selected files
   Dim wb As Workbook
   Dim wbPath As String

   If windowTitle = "" Then windowTitle = "Select one or more files to process"
   
showWindow:
   With Application.FileDialog(msoFileDialogFilePicker)
      .Filters.Clear
      .Title = windowTitle
      .InitialFileName = ThisWorkbook.Path & "\" ' 仅设置默认打开目录,不再用它做筛选
      ' --- 关键修改:添加自定义筛选规则,支持Orders和Registrations两类文件 ---
      .Filters.Add "Orders & Registrations Files", "*Orders*.xl*;*Registrations*.xl*"
      .Filters.Add "All Excel Files", "*.xl*;*.xm*" ' 保留全Excel文件筛选作为备选
      ' --- 结束修改 ---
      .AllowMultiSelect = multiSelect
      ' 移除原来用InitialFileName设置筛选的错误代码
      If .Show = -1 Then ' 如果用户点击确定
         wbPath = .SelectedItems(1)
      End If
                
      'If inArray(.SelectedItems, ThisWorkbook.FullName) <> -1 Then finishProgram ("You can't select this Workbook.")
      
      Set getFiles = .SelectedItems
   End With
   
   Select Case getFiles.Count
      Case 0:  End
      Case Is > maxSelected: GoTo showWindow
      Case Else: ' 继续执行
   End Select
   
   'If wbPath = "" Then End  'if no file chosen, end the program 
End Function

关键说明

  1. 筛选规则格式:*Orders*.xl*表示所有文件名包含Orders的Excel文件,*Registrations*.xl*同理,两者用分号分隔即可同时生效
  2. 默认路径保留:InitialFileName仅设置为工作簿所在路径,避免覆盖路径导致打开错误目录
  3. 备选筛选保留:保留全Excel文件筛选,方便用户在需要时切换查看所有Excel文件(如果不需要可以删除这一行)

内容的提问来源于stack exchange,提问作者David

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 05:23:16