【问题标题】:Find file in sub directory在子目录中查找文件
【发布时间】:2018-03-23 09:41:57
【问题描述】:

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

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

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 中的代码,但我在最后一行收到“类型不匹配”错误消息

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

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

【问题讨论】:

    标签: vba file subdirectory


    【解决方案1】:

    您的第二个代码与第一个代码不同,后者在给定文件夹(和子文件夹)中搜索名称恰好为 "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的最后一个位置生成一个空条目

    【讨论】:

      【解决方案2】:

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

      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
      

      【讨论】:

      • 感谢 QHarr。我在最后一行仍然遇到同样的错误
      • 当您遇到错误时,如果您输入 ?f & Application.PathSeparator & ibox 并回车,您会在即时窗口中得到什么?
      猜你喜欢
      • 2012-11-12
      • 1970-01-01
      • 1970-01-01
      • 2013-10-21
      • 2020-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多