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

VBA使用FileDialog文件对话框按文件名过滤文件的实现咨询

问题解答

可以实现。Office原生的FileDialog筛选器仅支持按文件后缀规则过滤,无法直接在弹窗选择阶段排除包含指定关键字的文件,因此我们可以在获取选中文件列表后的遍历环节增加判断逻辑,跳过文件名包含Conflicted的文件即可,改动量极小。

修改后完整代码

Sub OpenMultipleFiles()
Dim fd As FileDialog
Dim fileChosen As Integer
Dim basename As String
Dim fso As Variant
Set fso = CreateObject("Scripting.FileSystemObject")
Set fd = Application.FileDialog(msoFileDialogFilePicker)
basename = fso.getBaseName(ActiveWorkbook.Name)
fd.InitialFileName = ActiveWorkbook.Path ' Set Default Location to the Active Workbook Path
fd.InitialView = msoFileDialogViewList
fd.AllowMultiSelect = True
fd.Filters.Add "All supported files", "*.xlsm"

fileChosen = fd.Show
If fileChosen = -1 Then

    StartAlgo

    Dim myArray As Variant
    Dim FullPath As String
    Dim FileName As String
    Dim x As Long
    
    'open each of the files chosen
    For x = 1 To fd.SelectedItems.Count
        FullPath = fd.SelectedItems(x)
        FileName = fso.getFileName(fd.SelectedItems(x))
        ' 新增判断:跳过文件名包含Conflicted的文件
        If InStr(1, FileName, "Conflicted", vbTextCompare) = 0 Then
            CopyContractTbls FullPath, FileName
        End If
    Next x

    EndAlgo
Else
    MsgBox "Aborted"
    Exit Sub
End If

End Sub

改动说明

  • 仅在原代码的遍历选中文件循环内新增了判断逻辑,使用InStr函数检测文件名是否包含Conflicted关键字,仅不包含关键字的文件才会执行后续的导入逻辑
  • 代码中使用vbTextCompare参数表示匹配时不区分大小写,如果你需要严格区分大小写,将该参数替换为vbBinaryCompare即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 05:18:02