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

Excel VBA搜索K盘文件无法遍历子文件夹问题咨询

问题原因

  • 核心问题是VBA内置的Dir函数默认仅检索指定路径的一级目录,你当前的代码没有添加递归遍历子文件夹的逻辑,自然无法扫描到K盘根目录之外子文件夹里的匹配文件。
  • 次要问题:你定义的路径K:\\多写了一个反斜杠,VBA中本地路径仅需写K:\即可,不过该问题不影响核心检索逻辑。

修正方案

使用Scripting.FileSystemObject实现递归遍历,兼容性更好、逻辑更清晰,修正后完整代码如下:

Sub SearchRGFile()
    Dim RGNumber As String
    Dim rootPath As String
    Dim fso As Object
    Dim rootFolder As Object
    
    ' 晚绑定FileSystemObject,无需手动添加引用
    Set fso = CreateObject("Scripting.FileSystemObject")
    rootPath = "K:\"
    RGNumber = InputBox("Input RG-Number (33xxxx)", "RG-Number")
    If RGNumber = "" Then Exit Sub ' 点击取消直接退出程序
    
    Set rootFolder = fso.GetFolder(rootPath)
    ' 调用递归遍历子文件夹的过程
    Call RecursiveSearch(rootFolder, RGNumber, fso)
    
    Set fso = Nothing
    Set rootFolder = Nothing
End Sub

' 递归搜索子文件夹的独立过程
Sub RecursiveSearch(currentFolder As Object, targetNum As String, fso As Object)
    Dim subFolder As Object
    Dim file As Object
    
    ' 先遍历当前文件夹下的所有文件
    For Each file In currentFolder.Files
        If LCase(file.Name) Like "*" & LCase(targetNum) & "*.xlsm" Then
            Workbooks.Open file.Path
            Exit For ' 找到匹配文件就打开,要打开所有匹配文件删掉这行即可
        End If
    Next
    
    ' 再遍历所有子文件夹,递归调用搜索逻辑
    For Each subFolder In currentFolder.SubFolders
        Call RecursiveSearch(subFolder, targetNum, fso)
    Next
End Sub

补充说明

  • 如果K盘存储的文件量级较大,遍历过程可能需要数秒时间,属于正常情况。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 10:42:02