Vba 在子目录中查找文件
我需要在VBA中执行一个代码,以便在子目录中查找文件 如果我指定完整的目录,我可以使用本文中“brettdj”中的代码找到该文件Vba 在子目录中查找文件,vba,file,subdirectory,Vba,File,Subdirectory,我需要在VBA中执行一个代码,以便在子目录中查找文件 如果我指定完整的目录,我可以使用本文中“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") >
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
关于为什么上面的代码不起作用,如果有一个更好的方法来搜索文件的子文件夹?有什么想法? 对于底层的人不要忘记用扩展名来完全限定文件名,并考虑使用路径分隔符来连接。例如:
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
对于底层,不要忘记用扩展名对文件名进行完全限定,并考虑使用路径分隔符来连接。例如:
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
,因为有一个结尾vbCrlf
在sn
的最后一个位置生成一个空条目。您的第二个代码与第一个不同,因为后者搜索给定文件夹(和子文件夹)中名称完全相同的任何文件“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
由于有一个结尾vbCrlf
在sn
的最后一个位置生成了一个空条目,谢谢QHarr。我在最后一行仍然得到了相同的错误当你有错误时,如果你放上f&Application.PathSeparator&ibox并点击enter,你会在即时窗口中得到什么?谢谢QHarr。我仍然得到相同的error在最后一行出现错误时,如果放置f&Application.PathSeparator&ibox并按enter键,会在即时窗口中得到什么?