在子目录中查找文件

Find file in sub directory

我需要在 VBA 中编写代码以在子目录中查找文件。

使用 'brettdj' 中的代码 link 如果我指定完整目录,我可以找到该文件

Sub LoopThroughFiles()
    Dim MyObj As Object, MySource As Object, file As Variant
    file = Dir("\A\B\C\D\")
    While (file <> "")
        If InStr(file, "701000034955") > 0 Then
            MsgBox "found " & file
            Exit Sub
        End If
    file = Dir
  Wend
End Sub

我正在寻找不必指定完整目录的原因。

我尝试了此 link 中的代码,但在最后一行 'type mistmatch' 中收到错误消息

Sub Find_Files()       
    f = "\A\B\"        
    ibox = "701000034955"        
    sn = Split(CreateObject("wscript.shell").exec("cmd /c Dir """ & f & ibox & """ /s /a /b").stdout.readall, vbCrLf)         
    Sheets("Sheet1").[A1].Resize(UBound(sn) + 1) = Application.Transpose(sn) ' I get an error message in this line    
End Sub

关于为什么上面的代码不起作用以及是否有更好的解决方案来在子文件夹中搜索文件有什么想法吗?

对于底部,不要忘记用扩展名完全限定文件名,并考虑使用路径分隔符进行连接。例如:

Sub Find_Files()

    Dim f As String

    f = ThisWorkbook.Path
    ibox = "701000034955.xlsb"
    sn = Split(CreateObject("wscript.shell").exec("cmd /c Dir """ & f & Application.PathSeparator & ibox & """ /s /a /b").stdout.readall, vbCrLf)
    Sheets("Sheet1").[A1].Resize(UBound(sn) + 1) = Application.Transpose(sn)

End Sub

您的第二个代码与第一个代码的不同之处在于,后者会搜索给定文件夹(和子文件夹)中名称恰好为 "701000034955" 的任何文件,而前者会搜索名称 包含 那个字符串

的文件

因此我猜你只需要使用一些通配符

ibox = "*701000034955*" 
sn = Split(CreateObject("wscript.shell").exec("cmd /c Dir """ & f & Application.PathSeparator & ibox & """ /s /a /b").stdout.readall, vbCrLf)
Sheets("Sheet1").[A1].Resize(UBound(sn)) = Application.Transpose(sn)

请注意调整大小是 UBound(sn) 而不是 UBound(sn) + 1 因为有一个结尾 vbCrlfsn

的最后位置生成一个空条目