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

自定义目录搜索指定文件名文件及VBA代码报错咨询

解决VBA文件搜索的运行时错误445及高效实现方案

嘿,我来帮你搞定这个问题!你遇到的运行时错误'445',核心原因是Application.FileSearch这个对象早在Excel 2007版本就被微软移除了,所以现在的Excel版本根本不支持这个操作。接下来我给你两种靠谱的替代方案,既能满足你搜索包含指定文件名的需求,还能保证效率。

需求回顾

你需要:

  • 在C:\myTestDirectory及其子文件夹中搜索
  • 找出所有文件名包含myFileName(比如你示例中的"ABC123")的文件
  • 文件命名格式类似xxx__description__myFileName__YYMMDD.txt,存在多个版本

方案一:使用FileSystemObject(稳定高效,适合大量文件)

这个方法需要引用脚本库,处理子文件夹和大量文件时更稳定。

步骤1:添加引用

打开VBA编辑器 → 工具 → 引用 → 勾选Microsoft Scripting Runtime

代码实现

Sub FindFiles_FileSystemObject()
    Dim fso As New FileSystemObject
    Dim targetFolder As Folder
    Dim myFileName As String
    
    myFileName = "ABC123" ' 你的目标文件名关键词
    Set targetFolder = fso.GetFolder("C:\myTestDirectory")
    
    ' 调用递归函数搜索文件
    RecursiveFileSearch targetFolder, myFileName
    
    Set fso = Nothing
    Set targetFolder = Nothing
End Sub

Private Sub RecursiveFileSearch(currentFolder As Folder, searchKey As String)
    Dim file As File
    Dim subFolder As Folder
    
    ' 遍历当前文件夹中的文件
    For Each file In currentFolder.Files
        ' 判断文件名是否包含搜索关键词(不区分大小写)
        If InStr(1, file.Name, searchKey, vbTextCompare) > 0 Then
            Debug.Print file.Path ' 输出文件完整路径到立即窗口
        End If
    Next file
    
    ' 递归遍历子文件夹
    For Each subFolder In currentFolder.SubFolders
        RecursiveFileSearch subFolder, searchKey
    Next subFolder
End Sub

方案二:使用Dir函数(轻量无需引用,适合简单场景)

这个方法不需要额外引用,代码更简洁,适合文件数量不多的场景。

代码实现

Sub FindFiles_Dir()
    Dim myFileName As String
    Dim searchPath As String
    
    myFileName = "ABC123"
    searchPath = "C:\myTestDirectory\"
    
    ' 开始递归搜索
    RecursiveDir searchPath, "*" & myFileName & "*"
End Sub

Private Sub RecursiveDir(path As String, filePattern As String)
    Dim currentFile As String
    Dim subDir As String
    
    ' 搜索当前文件夹中的匹配文件
    currentFile = Dir(path & filePattern)
    Do While currentFile <> ""
        Debug.Print path & currentFile
        currentFile = Dir
    Loop
    
    ' 递归搜索子文件夹
    subDir = Dir(path & "*", vbDirectory)
    Do While subDir <> ""
        If subDir <> "." And subDir <> ".." Then
            If (GetAttr(path & subDir) And vbDirectory) = vbDirectory Then
                RecursiveDir path & subDir & "\", filePattern
            End If
        End If
        subDir = Dir
    Loop
End Sub

效率说明

  • 如果你的目录下文件和子文件夹非常多,FileSystemObject的稳定性更好,出错概率低;
  • 如果只是简单的小目录搜索,Dir函数更轻量,启动更快;
  • 两种方法都支持递归搜索子文件夹,且都是按文件名匹配,完全符合你的需求。

另外要注意,你原来的代码里把myFileName变量硬编码到了*.myFileName*.xlsx里,这会导致搜索的是字面量"myFileName"而不是你定义的变量值,上面的代码已经修正了这个问题,用"*" & myFileName & "*"来动态拼接搜索模式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:50:55