VBA遍历所有文件夹的两种方法(filesearch和FileSystemObject)
- 格式:doc
- 大小:28.50 KB
- 文档页数:1
垃圾百度文库,非说我文档质量低,害我复制这么多,双横线以后是复制品,大家不用看这段代码是我在网上找到的,速度很快,有需要的朋友保存下吧执行前先加个command,一■个listbox'遍历文件夹Private Sub ShowFolderList(folderspec)Dim fs, f, f1, s, sfDim hs, h, h1, hfSet fs = CreateObject("Scripting.FileSystemObject")Set f = fs.GetFolder(folderspec)Set sf = f.SubFoldersFor Each f1 In sfList1.AddItem folderspec & "\" & Call ShowFolderList(folderspec & "\" & )NextEnd Sub'遍历某文件夹下的文件Private Sub Showfilelist(folderspec)Dim fs, f, f1, fc, sSet fs = CreateObject("Scripting.FileSystemObject")Set f = fs.GetFolder(folderspec)Set fc = f.FilesFor Each f1 In fcList1.AddItem NextEnd Sub'遍历某文件夹及子文件夹中的所有文件Sub SosuoFile(MyPath As String)Dim Myname As StringDim a As StringDim B() As StringDim dir_i() As StringDim i, idir As LongIf Right(MyPath, 1) <> "\" Then MyPath = MyPath + "\"Myname = Dir(MyPath, vbDirectory Or vbHidden Or vbNormal Or vbReadOnly)Do While Myname <> ""If Myname <> "." And Myname <> ".." ThenIf (GetAttr(MyPath & Myname) And vbDirectory) = vbDirectory Then '如果找到的是目录idir= idir + 1ReDim Preserve dir_i(idir) As Stringdir_i(idir - 1) = MynameElseList1.AddItem MyPath & Myname '把找到的文件显示到列表框中End IfEnd IfMyname = Dir '搜索下一项LoopFor i = 0 To idir - 1Call SosuoFile(MyPath + dir_i(i))Next iReDim dir_i(0) As StringEnd Sub'附:'在这里可以处理目录中的文件' '得到文件名'Fn.Size '得到文件大小'Fn.Path '得到文件路径'Fn.Type '得到文件类型'Fn.DateLastModified '得到文件最后的修改日期'调用方法'ShowFolderList ("c:\a") 查找目录'Showfilelist ("c:\a") 查找文件'SosuoFile ("c:\a")查找目录+文件'遍历文件夹Private Sub ShowFolderList(folderspec)Dim fs, f, f1, s, sfDim hs, h, h1, hfSet fs = CreateObject("Scripting.FileSystemObject")Set f = fs.GetFolder(folderspec)Set sf = f.SubFoldersFor Each f1 In sfList1.AddItem folderspec & "\" & Call ShowFolderList(folderspec & "\" & ) NextEnd Sub'遍历某文件夹下的文件Private Sub Showfilelist(folderspec)Dim fs, f, f1, fc, sSet fs = CreateObject("Scripting.FileSystemObject")Set f = fs.GetFolder(folderspec)Set fc = f.FilesFor Each f1 In fcList1.AddItem NextEnd Sub'遍历某文件夹及子文件夹中的所有文件Sub SosuoFile(MyPath As String)Dim Myname As StringDim a As StringDim B() As StringDim dir_i() As StringDim i, idir As LongIf Right(MyPath, 1) <> "\" Then MyPath = MyPath + "\"Myname = Dir(MyPath, vbDirectory Or vbHidden Or vbNormal Or vbReadOnly)Do While Myname <> ""If Myname <> "." And Myname <> ".." ThenIf (GetAttr(MyPath & Myname) And vbDirectory) = vbDirectory Then '如果找到的是目录idir = idir + 1ReDim Preserve dir_i(idir) As Stringdir_i(idir - 1) = MynameElseList1.AddItem MyPath & Myname '把找到的文件显示到列表框中End IfEnd IfMyname = Dir '搜索下一项LoopFor i = 0 To idir - 1Call SosuoFile(MyPath + dir_i(i))Next iReDim dir_i(0) As StringEnd Sub'附:'在这里可以处理目录中的文件' '得到文件名'Fn.Size '得到文件大小'Fn.Path '得到文件路径'Fn.Type '得到文件类型'Fn.DateLastModified '得到文件最后的修改日期'调用方法'ShowFolderList ("c:\a") 查找目录'Showfilelist ("c:\a") 查找文件'SosuoFile ("c:\a") 查找目录+文件 '遍历文件夹Private Sub ShowFolderList(folderspec)Dim fs, f, f1, s, sfDim hs, h, h1, hfSet fs = CreateObject("Scripting.FileSystemObject")Set f = fs.GetFolder(folderspec)Set sf = f.SubFoldersFor Each f1 In sfList1.AddItem folderspec & "\" & Call ShowFolderList(folderspec & "\" & ) NextEnd Sub'遍历某文件夹下的文件Private Sub Showfilelist(folderspec)Dim fs, f, f1, fc, sSet fs = CreateObject("Scripting.FileSystemObject")Set f = fs.GetFolder(folderspec)Set fc = f.FilesFor Each f1 In fcList1.AddItem NextEnd Sub'遍历某文件夹及子文件夹中的所有文件Sub SosuoFile(MyPath As String)Dim Myname As String Dim a As String Dim B() As String Dim dir_i() As String Dim i, idir As LongIf Right(MyPath, 1) <> "\" Then MyPath = MyPath + "\"Myname = Dir(MyPath, vbDirectory Or vbHidden Or vbNormal Or vbReadOnly) Do While Myname <> ""If Myname <> "." And Myname <> ".." ThenIf (GetAttr(MyPath & Myname) And vbDirectory) = vbDirectory Then '如果找到的是目录 idir = idir + 1ReDim Preserve dir_i(idir) As String dir_i(idir - 1) = Myname ElseList1.AddItem MyPath & Myname '把找到的文件显示到列表框中End If End IfMyname = Dir '搜索下一项 LoopFor i = 0 To idir - 1Call SosuoFile(MyPath + dir_i(i)) Next iReDim dir_i(0) As String End Sub'附:'在这里可以处理目录中的文件'得到文件名 '得到文件大小 '得到文件路径 '得到文件类型'调用方法'ShowFolderList ("c:\a") 查找目录 'Showfilelist ("c:\a") 查找文件'SosuoFile ("c:\a") 查找目录+文件 '遍历文件夹 Private Sub ShowFolderList(folderspec)Dim fs, f, f1, s, sf Dim hs, h, h1, hfSet fs = CreateObject("Scripting.FileSystemObject") Set f = fs.GetFolder(folderspec) Set sf = f.SubFolders For Each f1 In sfList1.AddItem folderspec & "\" & ' 'Fn.Size 'Fn.Path 'Fn.Type'Fn.DateLastModified'得到文件最后的修改日期Call ShowFolderList(folderspec & "\" & )NextEnd Sub'遍历某文件夹下的文件Private Sub Showfilelist(folderspec)Dim fs, f, f1, fc, sSet fs = CreateObject("Scripting.FileSystemObject")Set f = fs.GetFolder(folderspec)Set fc = f.FilesFor Each f1 In fcList1.AddItem NextEnd Sub'遍历某文件夹及子文件夹中的所有文件Sub SosuoFile(MyPath As String)Dim Myname As StringDim a As StringDim B() As StringDim dir_i() As StringDim i, idir As LongIf Right(MyPath, 1) <> "\" Then MyPath = MyPath + "\"Myname = Dir(MyPath, vbDirectory Or vbHidden Or vbNormal Or vbReadOnly)Do While Myname <> ""If Myname <> "." And Myname <> ".." ThenIf (GetAttr(MyPath & Myname) And vbDirectory) = vbDirectory Then '如果找到的是目录idir = idir + 1ReDim Preserve dir_i(idir) As Stringdir_i(idir - 1) = MynameElseList1.AddItem MyPath & Myname '把找到的文件显示到列表框中End IfEnd IfMyname = Dir '搜索下一项LoopFor i = 0 To idir - 1Call SosuoFile(MyPath + dir_i(i))Next iReDim dir_i(0) As StringEnd Sub'附:'在这里可以处理目录中的文件' '得到文件名'Fn.Size '得到文件大小'Fn.Path '得到文件路径'Fn.Type '得到文件类型'Fn.DateLastModified '得到文件最后的修改日期'调用方法'ShowFolderList ("c:\a") 查找目录'Showfilelist ("c:\a") 查找文件'SosuoFile ("c:\a") 查找目录+文件 '遍历文件夹Private Sub ShowFolderList(folderspec)Dim fs, f, f1, s, sfDim hs, h, h1, hfSet fs = CreateObject("Scripting.FileSystemObject")Set f = fs.GetFolder(folderspec)Set sf = f.SubFoldersFor Each f1 In sfList1.AddItem folderspec & "\" & Call ShowFolderList(folderspec & "\" & ) NextEnd Sub'遍历某文件夹下的文件Private Sub Showfilelist(folderspec)Dim fs, f, f1, fc, sSet fs = CreateObject("Scripting.FileSystemObject")Set f = fs.GetFolder(folderspec)Set fc = f.FilesFor Each f1 In fcList1.AddItem NextEnd Sub'遍历某文件夹及子文件夹中的所有文件Sub SosuoFile(MyPath As String)Dim Myname As StringDim a As StringDim B() As StringDim dir_i() As StringDim i, idir As LongIf Right(MyPath, 1) <> "\" Then MyPath = MyPath + "\"Myname = Dir(MyPath, vbDirectory Or vbHidden Or vbNormal Or vbReadOnly)Do While Myname <> ""If Myname <> "." And Myname <> ".." ThenIf (GetAttr(MyPath & Myname) And vbDirectory) = vbDirectory Then '如果找到的是目录idir = idir + 1ReDim Preserve dir_i(idir) As Stringdir_i(idir - 1) = MynameElseList1.AddItem MyPath & Myname '把找到的文件显示到列表框中End IfEnd IfMyname = Dir '搜索下一项LoopFor i = 0 To idir - 1Call SosuoFile(MyPath + dir_i(i))Next iReDim dir_i(0) As StringEnd Sub'附:'在这里可以处理目录中的文件' '得到文件名'Fn.Size '得到文件大小'Fn.Path '得到文件路径'Fn.Type '得到文件类型'得到文件最后的修改日期'Fn.DateLastModified'调用方法'ShowFolderList ("c:\a") 查找目录'Showfilelist ("c:\a") 查找文件'SosuoFile ("c:\a") 查找目录+文件 '遍历文件夹Private Sub ShowFolderList(folderspec)Dim fs, f, f1, s, sfDim hs, h, h1, hfSet fs = CreateObject("Scripting.FileSystemObject")Set f = fs.GetFolder(folderspec)Set sf = f.SubFoldersFor Each f1 In sfList1.AddItem folderspec & "\" & Call ShowFolderList(folderspec & "\" & )NextEnd Sub'遍历某文件夹下的文件Private Sub Showfilelist(folderspec)Dim fs, f, f1, fc, sSet fs = CreateObject("Scripting.FileSystemObject")Set f = fs.GetFolder(folderspec)Set fc = f.FilesFor Each f1 In fcList1.AddItem NextEnd Sub'遍历某文件夹及子文件夹中的所有文件Sub SosuoFile(MyPath As String)Dim Myname As StringDim a As StringDim B() As StringDim dir_i() As StringDim i, idir As LongIf Right(MyPath, 1) <> "\" Then MyPath = MyPath + "\"Myname = Dir(MyPath, vbDirectory Or vbHidden Or vbNormal Or vbReadOnly)Do While Myname <> ""If Myname <> "." And Myname <> ".." ThenIf (GetAttr(MyPath & Myname) And vbDirectory) = vbDirectory Then '如果找到的是目录idir = idir + 1ReDim Preserve dir_i(idir) As Stringdir_i(idir - 1) = MynameElseList1.AddItem MyPath & Myname '把找到的文件显示到列表框中End IfEnd IfMyname = Dir '搜索下一项LoopFor i = 0 To idir - 1Call SosuoFile(MyPath + dir_i(i))Next iReDim dir_i(0) As StringEnd Sub'附:'在这里可以处理目录中的文件' '得到文件名'Fn.Size '得到文件大小'Fn.Path '得到文件路径'Fn.Type '得到文件类型'Fn.DateLastModified '得到文件最后的修改日期'调用方法'ShowFolderList ("c:\a") 查找目录'Showfilelist ("c:\a") 查找文件'SosuoFile ("c:\a") 查找目录+文件 '遍历文件夹Private Sub ShowFolderList(folderspec)Dim fs, f, f1, s, sfDim hs, h, h1, hfSet fs = CreateObject("Scripting.FileSystemObject")Set f = fs.GetFolder(folderspec)Set sf = f.SubFoldersFor Each f1 In sfList1.AddItem folderspec & "\" & Call ShowFolderList(folderspec & "\" & ) Next End Sub'遍历某文件夹下的文件Private Sub Showfilelist(folderspec)Dim fs, f, f1, fc, sSet fs = CreateObject("Scripting.FileSystemObject")Set f = fs.GetFolder(folderspec)Set fc = f.FilesFor Each f1 In fcList1.AddItem NextEnd Sub'遍历某文件夹及子文件夹中的所有文件Sub SosuoFile(MyPath As String)Dim Myname As StringDim a As StringDim B() As StringDim dir_i() As StringDim i, idir As LongIf Right(MyPath, 1) <> "\" Then MyPath = MyPath + "\"Myname = Dir(MyPath, vbDirectory Or vbHidden Or vbNormal Or vbReadOnly)Do While Myname <> ""If Myname <> "." And Myname <> ".." ThenIf (GetAttr(MyPath & Myname) And vbDirectory) = vbDirectory Then '如果找到的是目录idir = idir + 1ReDim Preserve dir_i(idir) As Stringdir_i(idir - 1) = MynameElseList1.AddItem MyPath & Myname '把找到的文件显示到列表框中End IfEnd IfMyname = Dir '搜索下一项LoopFor i = 0 To idir - 1Call SosuoFile(MyPath + dir_i(i))Next iReDim dir_i(0) As String End Sub'附:'在这里可以处理目录中的文件' '得到文件名'Fn.Size '得到文件大小'Fn.Path '得到文件路径'Fn.Type '得到文件类型'Fn.DateLastModified '得到文件最后的修改日期'调用方法'ShowFolderList ("c:\a") 查找目录'Showfilelist ("c:\a") 查找文件'SosuoFile ("c:\a") 查找目录+文件 '遍历文件夹Private Sub ShowFolderList(folderspec)Dim fs, f, f1, s, sfDim hs, h, h1, hfSet fs = CreateObject("Scripting.FileSystemObject")Set f = fs.GetFolder(folderspec)Set sf = f.SubFoldersFor Each f1 In sfList1.AddItem folderspec & "\" & Call ShowFolderList(folderspec & "\" & ) NextEnd Sub'遍历某文件夹下的文件Private Sub Showfilelist(folderspec)Dim fs, f, f1, fc, sSet fs = CreateObject("Scripting.FileSystemObject")Set f = fs.GetFolder(folderspec)Set fc = f.FilesFor Each f1 In fcList1.AddItem NextEnd Sub'遍历某文件夹及子文件夹中的所有文件Sub SosuoFile(MyPath As String)Dim Myname As StringDim a As StringDim B() As StringDim dir_i() As StringDim i, idir As LongIf Right(MyPath, 1) <> "\" Then MyPath = MyPath + "\"Myname = Dir(MyPath, vbDirectory Or vbHidden Or vbNormal Or vbReadOnly)Do While Myname <> ""If Myname <> "." And Myname <> ".." ThenIf (GetAttr(MyPath & Myname) And vbDirectory) = vbDirectory Then '如果找到的是目录idir = idir + 1ReDim Preserve dir_i(idir) As Stringdir_i(idir - 1) = MynameElseList1.AddItem MyPath & Myname '把找到的文件显示到列表框中End IfEnd IfMyname = Dir '搜索下一项LoopFor i = 0 To idir - 1Call SosuoFile(MyPath + dir_i(i))Next iReDim dir_i(0) As StringEnd Sub'附:'在这里可以处理目录中的文件' '得到文件名'Fn.Size '得到文件大小'Fn.Path '得到文件路径'Fn.Type '得到文件类型'Fn.DateLastModified '得到文件最后的修改日期'调用方法'ShowFolderList ("c:\a") 查找目录'Showfilelist ("c:\a") 查找文件'SosuoFile ("c:\a") 查找目录+文件'遍历文件夹Private Sub ShowFolderList(folderspec)Dim fs, f, f1, s, sfDim hs, h, h1, hfSet fs = CreateObject("Scripting.FileSystemObject")Set f = fs.GetFolder(folderspec)Set sf = f.SubFoldersFor Each f1 In sfList1.AddItem folderspec & "\" & Call ShowFolderList(folderspec & "\" & ) Next End Sub'遍历某文件夹下的文件Private Sub Showfilelist(folderspec)Dim fs, f, f1, fc, sSet fs = CreateObject("Scripting.FileSystemObject")Set f = fs.GetFolder(folderspec)Set fc = f.FilesFor Each f1 In fcList1.AddItem NextEnd Sub'遍历某文件夹及子文件夹中的所有文件Sub SosuoFile(MyPath As String)Dim Myname As StringDim a As StringDim B() As StringDim dir_i() As StringDim i, idir As LongIf Right(MyPath, 1) <> "\" Then MyPath = MyPath + "\"Myname = Dir(MyPath, vbDirectory Or vbHidden Or vbNormal Or vbReadOnly)Do While Myname <> ""If Myname <> "." And Myname <> ".." ThenIf (GetAttr(MyPath & Myname) And vbDirectory) = vbDirectory Then '如果找到的是目录idir = idir + 1ReDim Preserve dir_i(idir) As Stringdir_i(idir - 1) = MynameElseList1.AddItem MyPath & Myname '把找到的文件显示到列表框中End IfEnd IfMyname = Dir '搜索下一项LoopFor i = 0 To idir - 1Call SosuoFile(MyPath + dir_i(i))Next iReDim dir_i(0) As StringEnd Sub'附:'在这里可以处理目录中的文件' '得到文件名'Fn.Size '得到文件大小'Fn.Path '得到文件路径'Fn.Type '得到文件类型'Fn.DateLastModified '得到文件最后的修改日期'调用方法'ShowFolderList ("c:\a") 查找目录'Showfilelist ("c:\a") 查找文件'SosuoFile ("c:\a") 查找目录+文件 '遍历文件夹Private Sub ShowFolderList(folderspec)Dim fs, f, f1, s, sfDim hs, h, h1, hfSet fs = CreateObject("Scripting.FileSystemObject")Set f = fs.GetFolder(folderspec)Set sf = f.SubFoldersFor Each f1 In sfList1.AddItem folderspec & "\" & Call ShowFolderList(folderspec & "\" & )NextEnd Sub'遍历某文件夹下的文件Private Sub Showfilelist(folderspec)Dim fs, f, f1, fc, sSet fs = CreateObject("Scripting.FileSystemObject")Set f = fs.GetFolder(folderspec)Set fc = f.FilesFor Each f1 In fcList1.AddItem NextEnd Sub'遍历某文件夹及子文件夹中的所有文件Sub SosuoFile(MyPath As String)Dim Myname As StringDim a As StringDim B() As StringDim dir_i() As StringDim i, idir As LongIf Right(MyPath, 1) <> "\" Then MyPath = MyPath + "\"Myname = Dir(MyPath, vbDirectory Or vbHidden Or vbNormal Or vbReadOnly)Do While Myname <> ""If Myname <> "." And Myname <> ".." ThenIf (GetAttr(MyPath & Myname) And vbDirectory) = vbDirectory Then '如果找到的是目录idir = idir + 1ReDim Preserve dir_i(idir) As Stringdir_i(idir - 1) = MynameElseList1.AddItem MyPath & Myname '把找到的文件显示到列表框中End IfEnd IfMyname = Dir '搜索下一项LoopFor i = 0 To idir - 1Call SosuoFile(MyPath + dir_i(i))Next iReDim dir_i(0) As StringEnd Sub'附:'在这里可以处理目录中的文件' '得到文件名'Fn.Size '得到文件大小'Fn.Path '得到文件路径'Fn.Type '得到文件类型'Fn.DateLastModified '得到文件最后的修改日期'调用方法'ShowFolderList ("c:\a") 查找目录'Showfilelist ("c:\a") 查找文件'SosuoFile ("c:\a") 查找目录+文件 '遍历文件夹Private Sub ShowFolderList(folderspec)Dim fs, f, f1, s, sfDim hs, h, h1, hfSet fs = CreateObject("Scripting.FileSystemObject")Set f = fs.GetFolder(folderspec)Set sf = f.SubFoldersFor Each f1 In sfList1.AddItem folderspec & "\" & Call ShowFolderList(folderspec & "\" & ) Next End Sub'遍历某文件夹下的文件Private Sub Showfilelist(folderspec)Dim fs, f, f1, fc, sSet fs = CreateObject("Scripting.FileSystemObject")Set f = fs.GetFolder(folderspec)Set fc = f.FilesFor Each f1 In fcList1.AddItem NextEnd Sub'遍历某文件夹及子文件夹中的所有文件Sub SosuoFile(MyPath As String)Dim Myname As StringDim a As StringDim B() As StringDim dir_i() As StringDim i, idir As LongIf Right(MyPath, 1) <> "\" Then MyPath = MyPath + "\"Myname = Dir(MyPath, vbDirectory Or vbHidden Or vbNormal Or vbReadOnly) Do While Myname <> ""If Myname <> "." And Myname <> ".." ThenIf (GetAttr(MyPath & Myname) And vbDirectory) = vbDirectory Then '如果找到的是目录 idir = idir + 1ReDim Preserve dir_i(idir) As String dir_i(idir - 1) = Myname ElseList1.AddItem MyPath & Myname '把找到的文件显示到列表框中End If End IfMyname = Dir '搜索下一项 LoopFor i = 0 To idir - 1Call SosuoFile(MyPath + dir_i(i)) Next iReDim dir_i(0) As String End Sub'附:'在这里可以处理目录中的文件'得到文件名 '得到文件大小 '得到文件路径 '得到文件类型'调用方法'ShowFolderList ("c:\a") 查找目录 'Showfilelist ("c:\a") 查找文件'SosuoFile ("c:\a") 查找目录+文件 '遍历文件夹Private Sub ShowFolderList(folderspec)Dim fs, f, f1, s, sf Dim hs, h, h1, hfSet fs = CreateObject("Scripting.FileSystemObject") Set f = fs.GetFolder(folderspec) Set sf = f.SubFolders For Each f1 In sfList1.AddItem folderspec & "\" & Call ShowFolderList(folderspec & "\" & )Next End Sub' 'Fn.Size 'Fn.Path 'Fn.Type'Fn.DateLastModified '得到文件最后的修改日期'遍历某文件夹下的文件Private Sub Showfilelist(folderspec)Dim fs, f, f1, fc, sSet fs = CreateObject("Scripting.FileSystemObject")Set f = fs.GetFolder(folderspec)Set fc = f.FilesFor Each f1 In fcList1.AddItem NextEnd Sub'遍历某文件夹及子文件夹中的所有文件Sub SosuoFile(MyPath As String)Dim Myname As StringDim a As StringDim B() As StringDim dir_i() As StringDim i, idir As LongIf Right(MyPath, 1) <> "\" Then MyPath = MyPath + "\"Myname = Dir(MyPath, vbDirectory Or vbHidden Or vbNormal Or vbReadOnly)Do While Myname <> ""If Myname <> "." And Myname <> ".." ThenIf (GetAttr(MyPath & Myname) And vbDirectory) = vbDirectory Then '如果找到的是目录idir = idir + 1ReDim Preserve dir_i(idir) As Stringdir_i(idir - 1) = MynameElseList1.AddItem MyPath & Myname '把找到的文件显示到列表框中End IfEnd IfMyname = Dir '搜索下一项LoopFor i = 0 To idir - 1Call SosuoFile(MyPath + dir_i(i))Next iReDim dir_i(0) As StringEnd Sub'附:'在这里可以处理目录中的文件' '得到文件名'Fn.Size '得到文件大小'Fn.Path '得到文件路径'Fn.Type '得到文件类型'Fn.DateLastModified '得到文件最后的修改日期'调用方法'ShowFolderList ("c:\a") 查找目录'Showfilelist ("c:\a") 查找文件'SosuoFile ("c:\a") 查找目录+文件 '遍历文件夹Private Sub ShowFolderList(folderspec)Dim fs, f, f1, s, sfDim hs, h, h1, hfSet fs = CreateObject("Scripting.FileSystemObject")Set f = fs.GetFolder(folderspec)Set sf = f.SubFoldersFor Each f1 In sfList1.AddItem folderspec & "\" & Call ShowFolderList(folderspec & "\" & ) Next End Sub'遍历某文件夹下的文件Private Sub Showfilelist(folderspec)Dim fs, f, f1, fc, sSet fs = CreateObject("Scripting.FileSystemObject")Set f = fs.GetFolder(folderspec)Set fc = f.FilesFor Each f1 In fcList1.AddItem Next End Sub'遍历某文件夹及子文件夹中的所有文件Sub SosuoFile(MyPath As String) Dim Myname As String Dim a As String Dim B() As String Dim dir_i() As String Dim i, idir As LongIf Right(MyPath, 1) <> "\" Then MyPath = MyPath + "\"Myname = Dir(MyPath, vbDirectory Or vbHidden Or vbNormal Or vbReadOnly) Do While Myname <> ""If Myname <> "." And Myname <> ".." ThenIf (GetAttr(MyPath & Myname) And vbDirectory) = vbDirectory Then '如果找到的是目录 idir = idir + 1ReDim Preserve dir_i(idir) As String dir_i(idir - 1) = Myname ElseList1.AddItem MyPath & Myname '把找到的文件显示到列表框中End If End IfMyname = Dir '搜索下一项 LoopFor i = 0 To idir - 1Call SosuoFile(MyPath + dir_i(i)) Next iReDim dir_i(0) As String End Sub'附:'在这里可以处理目录中的文件'得到文件名 '得到文件大小 '得到文件路径 '得到文件类型'调用方法'ShowFolderList ("c:\a") 查找目录' 'Fn.Size 'Fn.Path 'Fn.Type'Fn.DateLastModified'得到文件最后的修改日期'Showfilelist ("c:\a") 查找文件'SosuoFile ("c:\a") 查找目录+文件 '遍历文件夹Private Sub ShowFolderList(folderspec)Dim fs, f, f1, s, sfDim hs, h, h1, hfSet fs = CreateObject("Scripting.FileSystemObject")Set f = fs.GetFolder(folderspec)Set sf = f.SubFoldersFor Each f1 In sfList1.AddItem folderspec & "\" & Call ShowFolderList(folderspec & "\" & )NextEnd Sub'遍历某文件夹下的文件Private Sub Showfilelist(folderspec)Dim fs, f, f1, fc, sSet fs = CreateObject("Scripting.FileSystemObject")Set f = fs.GetFolder(folderspec)Set fc = f.FilesFor Each f1 In fcList1.AddItem NextEnd Sub'遍历某文件夹及子文件夹中的所有文件Sub SosuoFile(MyPath As String)Dim Myname As StringDim a As StringDim B() As StringDim dir_i() As StringDim i, idir As LongIf Right(MyPath, 1) <> "\" Then MyPath = MyPath + "\"Myname = Dir(MyPath, vbDirectory Or vbHidden Or vbNormal Or vbReadOnly)Do While Myname <> ""If Myname <> "." And Myname <> ".." ThenIf (GetAttr(MyPath & Myname) And vbDirectory) = vbDirectory Then '如果找到的是目录idir = idir + 1ReDim Preserve dir_i(idir) As String dir_i(idir - 1) = MynameElseList1.AddItem MyPath & Myname '把找到的文件显示到列表框中End IfEnd IfMyname = Dir '搜索下一项LoopFor i = 0 To idir - 1Call SosuoFile(MyPath + dir_i(i))Next iReDim dir_i(0) As StringEnd Sub'附:'在这里可以处理目录中的文件' '得到文件名'Fn.Size '得到文件大小'Fn.Path '得到文件路径'Fn.Type '得到文件类型'Fn.DateLastModified '得到文件最后的修改日期'调用方法'ShowFolderList ("c:\a") 查找目录'Showfilelist ("c:\a") 查找文件'SosuoFile ("c:\a") 查找目录+文件 '遍历文件夹Private Sub ShowFolderList(folderspec)Dim fs, f, f1, s, sfDim hs, h, h1, hfSet fs = CreateObject("Scripting.FileSystemObject")Set f = fs.GetFolder(folderspec)Set sf = f.SubFoldersFor Each f1 In sfList1.AddItem folderspec & "\" & Call ShowFolderList(folderspec & "\" & ) NextEnd Sub'遍历某文件夹下的文件Private Sub Showfilelist(folderspec)Dim fs, f, f1, fc, sSet fs = CreateObject("Scripting.FileSystemObject")Set f = fs.GetFolder(folderspec)Set fc = f.FilesFor Each f1 In fcList1.AddItem NextEnd Sub'遍历某文件夹及子文件夹中的所有文件Sub SosuoFile(MyPath As String)Dim Myname As StringDim a As StringDim B() As StringDim dir_i() As StringDim i, idir As LongIf Right(MyPath, 1) <> "\" Then MyPath = MyPath + "\"Myname = Dir(MyPath, vbDirectory Or vbHidden Or vbNormal Or vbReadOnly)Do While Myname <> ""If Myname <> "." And Myname <> ".." ThenIf (GetAttr(MyPath & Myname) And vbDirectory) = vbDirectory Then '如果找到的是目录idir = idir + 1ReDim Preserve dir_i(idir) As Stringdir_i(idir - 1) = MynameElseList1.AddItem MyPath & Myname '把找到的文件显示到列表框中End IfEnd IfMyname = Dir '搜索下一项LoopFor i = 0 To idir - 1Call SosuoFile(MyPath + dir_i(i))Next iReDim dir_i(0) As StringEnd Sub'附:'在这里可以处理目录中的文件' '得到文件名'Fn.Size '得到文件大小'Fn.Path '得到文件路径'Fn.Type '得到文件类型'Fn.DateLastModified '得到文件最后的修改日期'调用方法'ShowFolderList ("c:\a") 查找目录'Showfilelist ("c:\a") 查找文件'SosuoFile ("c:\a") 查找目录+文件 '遍历文件夹Private Sub ShowFolderList(folderspec)Dim fs, f, f1, s, sfDim hs, h, h1, hfSet fs = CreateObject("Scripting.FileSystemObject")Set f = fs.GetFolder(folderspec)Set sf = f.SubFoldersFor Each f1 In sfList1.AddItem folderspec & "\" & Call ShowFolderList(folderspec & "\" & ) NextEnd Sub'遍历某文件夹下的文件Private Sub Showfilelist(folderspec)Dim fs, f, f1, fc, sSet fs = CreateObject("Scripting.FileSystemObject")Set f = fs.GetFolder(folderspec)Set fc = f.FilesFor Each f1 In fcList1.AddItem NextEnd Sub'遍历某文件夹及子文件夹中的所有文件Sub SosuoFile(MyPath As String)Dim Myname As StringDim a As StringDim B() As StringDim dir_i() As StringDim i, idir As LongIf Right(MyPath, 1) <> "\" Then MyPath = MyPath + "\"Myname = Dir(MyPath, vbDirectory Or vbHidden Or vbNormal Or vbReadOnly)Do While Myname <> ""If Myname <> "." And Myname <> ".." ThenIf (GetAttr(MyPath & Myname) And vbDirectory) = vbDirectory Then '如果找到的是目录idir = idir + 1ReDim Preserve dir_i(idir) As Stringdir_i(idir - 1) = MynameElse。
【VBA】遍历文件夹(含子文件夹)方法一、调用目标文件夹的方法1、Application.FileDialog方法Sub ListFilesT est()With Application.FileDialog(msoFileDialogFolderPicker) '运行后出现标准的选择文件夹对话框If .Show Then myPath = .SelectedItems(1) Else Exit Sub '如选中则返回=-1 / 取消未选则返回=0End WithIf Right(myPath, 1) <> '' Then myPath = myPath & '''返回的是选中目标文件夹的绝对路径,但除了本地C盘、D盘会以'C:'形式返回外,其余路径无''需要自己添加End Sub2、视窗浏览器界面选择目标文件夹Sub ListFilesT est()Set myFolder = CreateObject('Shell.Application').BrowseForFolder(0, 'GetFolder', 0)If Not myFolder Is Nothing Then myPath$ = myFolder.Items.Item.Path Else MsgBox 'Folder not Selected': Exit SubIf Right(myPath, 1) <> '' Then myPath = myPath & '''同样返回的是选中目标文件夹的绝对路径,但除了本地C盘、D盘会以'C:'形式返回外,其余路径无''需要添加End Sub二、仅列出所有文件不包括子文件夹、不包括子文件夹中的文件Sub ListFilesTest()With Application.FileDialog(msoFileDialogFolderPicker)If .Show ThenRight(myPath, 1) <> '' Then myPath = myPath & '''以上选择目标文件夹以得到路径myPath MsgBox ListFiles(myPath) '调用FSO的ListFiles过程返回目标文件夹下的所有文件名End SubFunction ListFiles(myPath$)Set fso = CreateObject('Scripting.FileSystemObject') '打开FSO脚本、建立FSO对象实例 For Each f In fso.GetFolder(myPath).Files '用FSO方法遍历指定文件夹内所有文件 i = i + 1: s = s & vbCr & '逐个列出文件名并统计文件个数 i Next ListFiles = i & ' Files:' & s '返回所有文件名的合并字符串End Function三、仅列出目标文件夹中所有子文件夹名不包括目标文件夹中文件、不包括子文件夹中的文件或子文件夹Sub ListFilesTest()With Application.FileDialog(msoFileDialogFolderPicker)If .Show Then myPath$ = .SelectedItems(1) Else Exit SubEnd WithIf Right(myPath, 1) <> '' Then myPath = myPath & '' MsgBox ListFolders(myPath)End SubFunction ListFolders(myPath$)Set fso = CreateObject('Scripting.FileSystemObject')For Each f In fso.GetFolder(myPath).SubFolders j = j + 1: t = t & vbCr & Next ListFolders = j & ' Folders:' & tEnd Functionfso.GetFolder(myPath).Filesfso.GetFolder(myPath).SubFolders四、遍历目标文件夹内所有文件、以及所有子文件夹中的所有文件【字典】Sub ListFilesTest() With Application.FileDialog(msoFileDialogFolderPicker) If .Show ThenRight(myPath, 1) <> '' Then myPath = myPath & ''MsgBox 'List Files:' & vbCr & Join(ListAllFsoDic(myPath), vbCr) MsgBox 'List SubFolders:' & vbCr & Join(ListAllFsoDic(myPath, 1), vbCr)End SubFunction ListAllFsoDic(myPath$, Optional k = 0) '使用2个字典但无需递归的遍历过程Dim i&, j& Set d1 = CreateObject('Scripting.Dictionary') '字典d1记录子文件夹的绝对路径名 Set d2 = CreateObject('Scripting.Dictionary') '字典d2记录文件名(文件夹和文件分开处理)d1(myPath) = '' '以当前路径myPath作为起始记录,以便开始循环检查Set fso = CreateObject('Scripting.FileSystemObject') Do While i < d1.Count '当字典1文件夹中有未遍历处理的key存在时进行Do循环直到 i=d1.Count即所有子文件夹都已处理时停止kr = d1.Keys '取出文件夹中所有的key即所有子文件夹路径(注意每次都要更新) For Each f In fso.GetFolder(kr(i)).Files '遍历该子文件夹中所有文件(注意仅从新的kr(i) 开始)j = j + 1: d2(j) = '把该子文件夹内的所有文件名作为字典Item项加入字典d2 (为防止文件重名不能用key属性) Nexti = i + 1 '已经处理过的子文件夹数目 i +1 (避免下次产生重复处理) For Each fd In fso.GetFolder(kr(i - 1)).SubFolders '遍历该文件夹中所有新的子文件夹 d1(fd.Path) = ' ' & & '' '把新的子文件夹路径存入字典d1以便在下一轮循环中处理 Next Loop If k Then ListAllFsoDic = d1.Keys Else ListAllFsoDic = d2.Items '如果参数=1则列出字典d1中所有子文件夹的路径名(如使用d1.Items则仅列出子文件夹名称不含路径) '如果参数=0则默认列出字典d2中Items即所有文件名 End Function【DIR】Sub ListAllDirDicTest() WithApplication.FileDialog(msoFileDialogFolderPicker) If .Show Then myPath$ = .SelectedItems(1) Else Exit Sub End With If Right(myPath, 1) <> '' Then myPath = myPath & ''MsgBox Join(ListAllDirDic(myPath), vbCr) 'GetAllSubFolder's File 列出目标文件夹内含子文件夹内所有文件MsgBox Join(ListAllDirDic(myPath, 1), vbCr) 'GetThisFolder's File 列出目标文件夹内所有文件(不含子文件夹)MsgBox Join(ListAllDirDic(myPath, -1), vbCr) 'GetThisFolder's SubFolder 仅列出目标文件夹内的子文件夹MsgBox Join(ListAllDirDic(myPath, -2), vbCr) 'GetAllSubFolder 列出目标文件夹内含子文件夹的所有子文件夹MsgBox Join(ListAllDirDic(myPath, 1, 'tst'), vbCr) 'GetThisFolder's SpecialFile 仅列出文件夹内含关键字文件 MsgBox Join(ListAllDirDic(myPath, , 'tst'), vbCr) 'GetAllSubFolder's SpecialFile 列出子文件夹内含关键字文件End SubFunction ListAllDirDic(myPath$, Optional sb& = 0, Optional SpFile$ = '') '利用Dir方法、以及用2个字典分别记录子文件夹路径和文件名的文件搜寻方法。
VBA批量处理文件和文件夹的技巧VBA(Visual Basic for Applications)是一种广泛应用于Microsoft Office套件中的编程语言,它可以帮助用户自动化和简化在Excel、Word、PowerPoint等应用中的重复操作。
对于需要处理大量文件和文件夹的任务,使用VBA可以大大提高效率。
本文将介绍一些VBA批量处理文件和文件夹的技巧,帮助用户在日常工作中更高效地完成相关任务。
1. 批量处理文件在VBA中,可以使用File System Object(文件系统对象)来访问和处理文件。
使用下面的代码可以批量处理指定文件夹中的所有文件:```vbaSub BatchProcessFiles()Dim FileSystem As ObjectDim SourceFolder As ObjectDim FileItem As Object' 设置源文件夹路径Set FileSystem = CreateObject("Scripting.FileSystemObject")Set SourceFolder = FileSystem.GetFolder("C:\SourceFolder")' 循环处理文件夹中的所有文件For Each FileItem In SourceFolder.Files' 在此处添加具体的文件处理逻辑' 例如,可以使用获取文件名' 若需要重新命名文件,可以使用 = "NewFileName"Next FileItem' 清除对象Set FileItem = NothingSet SourceFolder = NothingSet FileSystem = NothingEnd Sub```在上述代码中,我们首先使用`CreateObject("Scripting.FileSystemObject")`创建了一个文件系统对象,然后使用`GetFolder()`方法指定了源文件夹路径。
VBA遍历⽂件夹的三种⽅法VBA遍历⽂件夹常⽤有三种⽅法,这三种⽅法中,filesearch不适合2007和2010版本,⽽且速度⽐较慢,递归法速度也慢。
只有⽤DIR加循环的⽅法,速度飞快。
下⾯是三种⽅法的代码:1、filesearch法Sub test3()Dim wb As WorkbookDim i As LongDim tt = TimerWith Application.FileSearch '调⽤fileserch对象.NewSearch '开始新的搜索.LookIn = ThisWorkbook.path '设置搜索的路径.SearchSubFolders = True '搜索范围包括 LookIn 属性指定的⽂件夹中的所有⼦⽂件夹.Filename = "*.xls" '设置搜索的⽂件类型' .FileType = msoFileTypeExcelWorkbooksIf .Execute() > 0 Then '如果找到⽂件For i = 1 To .FoundFiles.Count'On Error Resume NextCells(i, 1) = .FoundFiles(i) '把找到的⽂件放在单元格⾥Next iElseMsgBox "没找到⽂件"End IfEnd WithMsgBox Timer - tEnd Sub2、递归法Sub Test()Dim iPath As String, i As LongDim tt = TimerWith Application.FileDialog(msoFileDialogFolderPicker).Title = "请选择要查找的⽂件夹"If .Show TheniPath = .SelectedItems(1)End IfEnd WithIf iPath = "False" Or Len(iPath) = 0 Then Exit Subi = 1Call GetFolderFile(iPath, i)MsgBox Timer - tMsgBox "⽂件名链接获取完毕。
VBA中的文件路径与文件名操作技巧VBA(Visual Basic for Applications)是一种广泛用于Microsoft Office应用程序中的编程语言。
在VBA中,文件路径和文件名操作是常见的需求,因为几乎所有的应用程序都需要与文件进行交互。
本文将介绍一些VBA中的文件路径和文件名操作技巧,帮助你更好地处理文件。
1. 获取文件路径获取文件路径是一个常见的需求,通常是为了打开文件、保存文件或对文件进行操作。
在VBA中,你可以使用FileSystemObject对象的GetAbsolutePathName方法来获取文件的绝对路径。
以下是一个示例代码:```Dim fso As ObjectSet fso = CreateObject("Scripting.FileSystemObject")Dim filePath As StringfilePath = fso.GetAbsolutePathName("filename.extension")```在这个示例代码中,你需要将"filename.extension"替换为你要操作的文件名和扩展名。
执行该代码后,`filePath`变量将保存文件的绝对路径。
另外,如果你想获取当前正在运行的VBA代码文件的路径,可以使用`ThisWorkbook.Path`方法。
这个方法提供了当前工作簿(Workbook)所在的目录路径。
2. 获取文件名获取文件名是另一个常见需求,有时你需要从文件路径中提取文件名。
VBA 提供了几种方法来获取文件名。
下面是两种常用的方法:方法一:使用FileSystemObject对象的GetFileName方法。
以下是一个示例代码:```Dim fso As ObjectSet fso = CreateObject("Scripting.FileSystemObject")Dim fileName As StringfileName = fso.GetFileName("C:\Folder\filename.extension")```在这个示例代码中,你需要将"C:\Folder\filename.extension"替换为你要操作的文件的绝对路径。
Excel:VBA 文件及文件夹操作2011年06月12日星期日 09:08VBA文件及文件夹操作1.VBA操作文件及文件夹on error resume next下测试A,在D:\下新建文件夹,命名为folder方法1:MkDir "D:\folder"方法2:Set abc = CreateObject("Scripting.FileSystemObject")abc.CreateFolder ("D:\folder")B,新建2个文件命名为a.xls和b.xlsWorkbooks.AddActiveWorkbook.SaveAs Filename:="D:\folder\a.xls"ActiveWorkbook.SaveAs Filename:="D:\folder\b.xls"C,创建新文件夹folder1并把a.xls复制到新文件夹重新命名为c.xlsMkDir "D:\folder1"FileCopy "D:\folder\a.xls", "D:\folder1\c.xls"D,复制folder中所有文件到folder1Set qqq = CreateObject("Scripting.FileSystemObject")qqq.CopyFolder "D:\folder", "D:\folder1"D,重命名a.xls为d.xlsname "d:\folder1\a.xls" as "d:\folder1\d.xls"E,判断文件及文件夹是否存在Set yyy = CreateObject("Scripting.FileSystemObject")If yyy.FolderExists("D:\folder1) = True Then ...If yyy.FileExists("D:\folder1\d.xls) = True Then ...F,打开folder1中所有文件Set rrr = CreateObject("Scripting.FileSystemObject")Set r = rrr.GetFolder("d:\folder1")For Each i In r.FilesWorkbooks.Open Filename:=("d:\folder1\" + + "")NextG,删除文件c.xlskill "d:\folder1\c.xls"H,删除文件夹folderSet aaa = CreateObject("Scripting.FileSystemObject")aaa.DeleteFolder "d:\folder"2.excel vba一次性获取文件夹下的所有文件名的方法小生今天上网下载了一个财务常用报表的文件包,里面有几百个excel工作表,要是手工一个一个的获得文件名的话,那我可是要忙十天半月哦。
VBA编程中的文件路径与文件夹操作详解VBA是一种用于Excel、Word、Access等微软Office软件的编程语言,它的强大功能可以帮助用户自动化操作、处理数据和创建自定义应用程序。
在VBA编程的过程中,文件路径和文件夹操作是非常重要的,它们可以帮助我们定位和管理需要处理的文件和文件夹。
本文将详细介绍VBA编程中文件路径和文件夹操作的相关知识。
一、文件路径的操作在VBA中,文件路径可以用于定位需要处理的文件。
我们可以使用文件路径操作打开、保存、复制、移动等文件操作。
下面是一些常用的文件路径操作:1. 获取文件路径使用VBA获取当前文件的路径可以通过ActiveWorkbook.Path来实现。
这个属性返回的是一个字符串,即当前文件的完整路径。
我们可以将此路径赋值给一个变量,以便后续的文件操作使用。
2. 获取特定文件路径如果我们需要获取特定文件的路径,可以使用VBA的FileDialog函数。
通过设置FileDialog的属性,我们可以选择特定的文件类型和过滤器,然后返回所选文件的路径。
例如,以下代码演示了如何打开选择文件对话框并获取文件路径:```Sub GetFilePath()Dim filePath As StringWith Application.FileDialog(msoFileDialogFilePicker).AllowMultiSelect = False.Title = "选择文件".Filters.Add "Excel文件", "*.xlsx"If .Show = True ThenfilePath = .SelectedItems(1)End IfEnd WithEnd Sub```3. 打开文件使用VBA打开文件可以通过Workbooks.Open方法实现。
我们需要提供文件的完整路径作为参数,然后可以对该文件进行操作。
vba filesearch 用法VBA的FileSearch对象是一个强大的工具,它可以帮助您在文件系统中搜索文件。
通过使用FileSearch对象,您可以基于各种标准(如文件名、文件大小、修改日期等)来查找文件。
以下是FileSearch对象的基本用法:创建一个FileSearch对象:首先,您需要创建一个FileSearch对象。
vbaDim fs As FileSearchSet fs = New FileSearch定义搜索标准:使用Criteria属性来定义搜索标准。
您可以设置多个条件,这些条件将与逻辑运算符(如AND、OR)结合使用。
vbaWith fs.RootFolder = "C:\YourFolder" '指定搜索的根文件夹.FileName = "*.txt" '搜索所有txt文件.Size = "*" '可以设置文件大小条件.DateLastModified = "1/1/2020" '设置修改日期条件End With执行搜索:使用Execute方法执行搜索。
这将返回一个FoundFiles集合,其中包含所有匹配的文件。
vbaDim results As FoundFilesSet results = fs.Execute处理搜索结果:您可以使用FoundFiles集合的属性和方法来处理搜索结果。
例如,可以使用Count属性来获取匹配文件的数量,使用Item方法来访问特定的匹配文件。
vbaIf results.Count > 0 ThenFor i = 1 To results.CountDebug.Print results.Item(i).Name '打印文件名Next iElseMsgBox "没有找到匹配的文件。
"End If清理资源:完成搜索后,确保释放FileSearch对象所使用的资源。
用VBA遍历指定文件夹里包括子文件夹里的所有文件如何用VBA遍历指定文件夹内的所有文件?如果仅仅是指定文件夹下的文件而不包括子文件夹内文件的话,那好办。
一个Do...While加上Dir就可以搞定。
要包括子文件夹,那就要费一番小功夫了。
网上没有找到用Dir的完美答案,所以参考网上的思路,根据自己的理解编了一个,以备后用。
主要还是利用两个字典对象及递归的思想。
------------------------------------------------Sub test()Dim startfolder As Stringstartfolder = "D:\starcraft\" '指定文件夹Set folderlist = CreateObject("scripting.dictionary")Set filelist = CreateObject("scripting.dictionary")i = 1folderlist.Add startfolder, ""Do While folderlist.Count > 0For Each FolderName In folderlist.keysfname = Dir(FolderName, vbDirectory)Do While fname <> ""If fname <> ".." And fname <> "." ThenIf GetAttr(FolderName & fname) And vbDirectory Thenfolderlist.Add FolderName & fname & "\", ""Elsefilelist.Add FolderName & fname, "" '这里列出的该文件的路径+文件名End IfEnd Iffname = DirLoopfolderlist.Remove (FolderName)NextLoopFor Each arr In filelist.keys ‘将文件路径+文件名放在当前工作表的A列Range("A" & i).Value = arri = i + 1NextEnd Sub。
不久前有个朋友让我帮忙写段代码,可以一次性处理指定文件夹下(包括子文件夹下)所有Word文档,花了点时间终于得出了如下的代码。
首先,打开Office的宏编辑器,选择“工具”-“引用”,选中下面两个对象:Microsoft Scripting RuntimeMicrosoft Script Control 1.0代码如下:Sub T est()EnumFiles "e:" ' 遍历e: 下的所有文件End SubSub EnumFiles(ByVal sPath As String)Dim fs As New FileSystemObjectGetFile fs.GetFolder(sPath)Set fs = NothingEnd SubSub GetFile(ByVal fldParent As Folder)Dim fldSub As Folder, fSub As FileFor Each fldSub In fldParent.SubFoldersGetFile fldSubNextFor Each fSub In fldParent.FilesIf UCase(Right(Trim(fSub), 3)) = "DOC" Then ' 文件类型判断Debug.Print fSubEnd IfNextSet fldSub = NothingSet fSub = NothingEnd Sub经过这段时间在Excel和Word下面的宏的使用发现,原来在Office中使用VBA也是可以完成很多工作的。
打开D盘TEST下所有.xls的文件.Sub test()Dim sFolder As StringDim wb As WorkbookDim i As LongWith Application.FileSearch.NewSearch.LookIn = "D:\test".SearchSubFolders = True.Filename = "*.xls".FileType = msoFileTypeExcelWorkbooksIf .Execute() > 0 ThenFor i = 1 To .FoundFiles.CountOn Error Resume NextSet wb = Workbooks.Open(Filename:=.FoundFiles(i))Next iElseMsgBox "Folder " & sFolder & " contains no required files"End IfEnd WithExit Sub给个测试下,至于add新的workbook,自己改下吧Sub test()PathName = "c:\test"+ "\*.xls"dirna = Dir(PathName)i = 1Do While dirna <> ""Cells(i, 1) = Left(dirna, Len(dirna) - 10) & ".xls"i = i + 1dirna = DirLoopEnd SubSub ChgName()Dim Fdlg As FileDialog, FlDim Fso, Fld, Fln, WkSet Fdlg = Application.FileDialog(msoFileDialogFolderPicker) With Fdlg.InitialFileName = ThisWorkbook.Path & "\"If .Show Then Fl = .SelectedItems(1)End WithSet Fso = CreateObject("Scripting.FileSystemObject")Set Fld = Fso.GetFolder(Fl)Set Fln = Fld.FilesFor Each Wk In Fln = Left(, Len() - 10) & ".xls" NextEnd Sub'引用Microsoft Scripting RuntimePrivate Sub Command1_Click()Dim pFolder As String, fso As New FileSystemObjectpFolder = "D:\12"Dim objFile, objFolderSet objFolder = fso.getFolder(pFolder)For Each objFile In objFolder.FilesDebug.Print objFile.PathNextFor Each objFolder In objFolder.SubFoldersDebug.Print objFolderNextEnd SubPrivate Sub Command1_Click()MyProc1 "d:\"End SubSub MyProc1(ByVal Folder As String)Dim fso As New FileSystemObjectDim objFile, objFolderSet objFolder = fso.getFolder(Folder)For Each objFile In objFolder.FilesMyProc2 objFile.PathNextFor Each objFolder In objFolder.SubFoldersMyProc1 objFolder '递归遍历整颗树NextEnd SubSub MyProc2(FileName As String)Debug.Print FileNameEnd Sub。
VBA中的文件搜索与批量处理技巧VBA(Visual Basic for Applications)是一种用于自动化任务和定制Microsoft Office应用程序的编程语言。
在处理大量文件和数据时,文件搜索和批量处理是常见的需求。
在本文中,将介绍一些VBA中的文件搜索和批量处理技巧,帮助您更高效地处理文件和数据。
一、文件搜索技巧文件搜索是一项重要的任务,特别是在处理大量文件时。
VBA提供了许多功能和方法,可以帮助我们实现文件搜索。
1. 使用Dir函数:Dir函数是VBA中的一个基本文件查找函数。
通过指定文件路径和文件类型的参数,Dir函数可以返回匹配的文件名。
可以使用循环结构,遍历文件夹中的所有文件,并根据文件名的条件进行筛选。
2. 使用FileSystemObject:FileSystemObject是VBA中用于操作文件系统的对象。
它提供了更高级的文件搜索功能,可以搜索指定文件夹中的所有文件,甚至包括子文件夹。
使用FileSystemObject还可以获取文件的属性和路径等信息。
3. 限制搜索范围:为了提高文件搜索的效率,可以通过限制搜索范围来缩小搜索的范围。
例如,可以指定搜索的根文件夹,或者通过文件名的关键字进行筛选。
4. 使用通配符:通配符是一种用于模糊匹配文件名的符号。
在文件搜索中,使用通配符可以更灵活地匹配文件名。
例如,使用"*"通配符可以匹配任意字符,使用"?"通配符可以匹配任意单个字符。
二、文件批量处理技巧文件批量处理是指对多个文件进行相同操作或一系列操作的过程。
VBA提供了许多功能和方法,可以帮助我们实现文件批量处理。
1. 使用For Each循环:For Each循环是VBA中的一种循环结构,可以遍历集合中的所有对象。
通过使用For Each循环,可以遍历文件夹中的所有文件,并对每个文件执行相同的操作。
2. 使用FileSystemObject:如前所述,FileSystemObject是VBA中常用的文件操作对象。
VBA中的文件夹遍历技巧VBA是一种广泛使用的编程语言,用于在Microsoft Office套件中自动化任务。
其中一个常见的任务是在文件夹中查找特定类型的文件或处理文件夹中的所有文件。
为了实现这些功能,您需要了解VBA中的文件夹遍历技巧。
文件夹遍历是指迭代一个文件夹中的所有文件或子文件夹。
通过使用递归或循环结构,您可以遍历整个文件夹结构,并对其中的每个文件或文件夹执行所需的操作。
在VBA中,您可以使用File System Object(FSO)来遍历文件夹。
FSO提供了许多有用的方法和属性,可以帮助您处理文件夹和文件。
要使用FSO,请先添加对Microsoft Scripting Runtime库的引用,并在代码中声明一个FileSystemObject对象。
以下是一些常用的文件夹遍历技巧:1. 遍历文件夹中的所有文件:对于需要处理文件夹中的所有文件的任务,您可以使用File对象和Files集合来实现。
通过使用FSO的GetFolder方法,您可以获取指定路径下的文件夹对象。
然后,使用Files属性遍历该文件夹中的所有文件。
```vbaSub TraverseFiles()Dim FSO As ObjectDim Folder As ObjectDim File As ObjectSet FSO = CreateObject("Scripting.FileSystemObject") Set Folder = FSO.GetFolder("C:\Path\To\Folder\")For Each File In Folder.Files' 处理文件的操作Next FileSet FSO = NothingSet Folder = NothingSet File = NothingEnd Sub```2. 遍历文件夹中的所有子文件夹:如果您需要遍历文件夹及其所有子文件夹中的文件,可以使用Folders集合和File对象的递归方法。
VBA中的目录操作与文件搜索方法VBA(Visual Basic for Applications)是一种被广泛应用于Microsoft Office套件中的编程语言。
在使用VBA编写宏时,经常需要进行目录操作和文件搜索。
本文将介绍在VBA中进行目录操作和文件搜索的方法。
目录操作是指对目录(即文件夹)进行创建、重命名、删除等操作。
在VBA中,可以使用FileSystemObject对象来实现目录操作。
首先需要在代码的开头添加对Microsoft Scripting Runtime库的引用,然后声明一个FileSystemObject对象,如下所示:```vbaDim fs As ObjectSet fs = CreateObject("Scripting.FileSystemObject")```接下来,可以使用FileSystemObject来进行各种目录操作。
以下是几个常见的目录操作方法:1. 创建目录:使用CreateFolder方法可以创建一个新的目录。
示例如下:```vbafs.CreateFolder "C:\NewFolder"```2. 删除目录:使用DeleteFolder方法可以删除一个目录。
示例如下:```vbafs.DeleteFolder "C:\OldFolder"```3. 检查目录是否存在:使用FolderExists方法可以检查一个目录是否存在。
示例如下:```vbaIf fs.FolderExists("C:\ExistingFolder") ThenMsgBox "目录存在!"ElseMsgBox "目录不存在!"End If```除了目录操作,文件搜索也是VBA中常用的功能。
需要遍历目录中的文件,并根据一定的条件进行搜索。
以下是几个常见的文件搜索方法:1. 遍历目录中的文件:使用GetFolder方法可以获取一个目录的Folder对象,然后使用Files属性获取该目录中的所有文件。
VBA遍历所有文件夹的两种方法(filesearch和FileSystemObject)在VBA遍历文件夹和子文件夹中所有文件,常用两种方法,一种是使用VBA的filesercth 对象,另外一种是使用FileSystemObject(windows文件管理工具)和递归方法。
兰色对代码进行了注解,希望对大家有所帮助第一种方法:使用filesearch对象Sub mysearch()Dim fs, i, arr(1 To 10000)Set fs = Application.FileSearch '设置一个搜索对象With fs.LookIn = ThisWorkbook.Path & "/" '设置搜索路径.Filename = "*.xls" '要搜索文件名和类型.SearchSubFolders = True '是否需要搜索子文件夹If .Execute > 0 Then '如果找不到文件MsgBox "There were " & .FoundFiles.Count & _" file(s) found." '显示文件找不到For i = 1 To .FoundFiles.Count '通过循环把所有搜索到的文件存入到数组中arr(i) = .FoundFiles(i)Next iSheets(1).Range("A1").Resize(.FoundFiles.Count) = Application.Transpose(arr) ' '把数组内的路径和文件名放在单元格中ElseMsgBox "There were no files found."End IfEnd WithEnd Sub第二种方法:引用FileSystemObject对象注意:要使用FileSystemObject对象,需要首先引用一下,具体方法,VBE--工具--引用--找到miscrosoft scription runtime项目并选中代码及注释:Dim ArrFiles(1 To 10000) '创建一个数组空间,用来存放文件名称Dim cntFiles% '文件个数Public Sub ListAllFiles()Dim strPath$ '声明文件路径Dim i%'Set fso = CreateObject("Scripting.FileSystemObject")Dim fso As New FileSystemObject, fd As Folder '创建一个FileSystemObject对象和一个文件夹对象strPath = ThisWorkbook.Path & "\" '"设置要遍历的文件夹目录cntFiles = 0Set fd = fso.GetFolder(strPath) '设置fd文件夹对象SearchFiles fd '调用子程序查搜索文件Sheets(1).Range("A1").Resize(cntFiles) = Application.Transpose(ArrFiles) '把数组内的路径和文件名放在单元格中End SubSub SearchFiles(ByVal fd As Folder)Dim fl As FileDim sfd As FolderFor Each fl In fd.Files '通过循环把文件逐个放在数组内cntFiles = cntFiles + 1ArrFiles(cntFiles) = fl.PathNext flIf fd.SubFolders.Count = 0 Then Exit Sub 'SubFolders返回由指定文件夹中所有子文件夹(包括隐藏文件夹和系统文件夹)组成的 Folders 集合For Each sfd In fd.SubFolders '在 Folders 集合进行循环查找SearchFiles sfd '使用递归方法查找下一个文件夹NextEnd Sub。
VBA中的文件路径与文件查找技巧在使用VBA编程时,经常需要处理文件和文件路径的操作。
文件路径指的是文件的保存位置或者文件夹的位置,而文件查找技巧则是指通过VBA代码来查找文件或者在文件夹中搜索特定类型的文件。
掌握这些技巧将提高我们在VBA中处理文件操作的效率。
本文将介绍一些VBA中常用的文件路径与文件查找技巧,帮助读者更好地利用VBA来处理文件操作。
1. 获取当前工作目录的路径在VBA中,我们可以通过使用CurDir函数来获取当前工作目录的路径。
当前工作目录是指在进行文件操作时,默认情况下打开或保存文件的路径。
下面是一个简单的例子,演示如何使用CurDir函数获取当前工作目录的路径:```Sub GetCurrentDirectory()MsgBox CurDirEnd Sub```2. 获取特定文件的路径除了获取当前工作目录的路径,我们还经常需要获取特定文件的路径。
下面是两种不同的方法来获取特定文件的路径:- 使用FileDialog对话框选择文件路径使用VBA中的FileDialog对话框可以让用户选择文件,从而获取选择文件的路径。
以下是一个使用FileDialog对话框选择文件路径的示例:```Sub GetFilePath()Dim fileDialog As FileDialogDim selectedFile As VariantSet fileDialog = Application.FileDialog(msoFileDialogFilePicker) With fileDialog.Title = "请选择文件".Filters.Add "Excel文件", "*.xlsx".AllowMultiSelect = FalseIf .Show = -1 Then ' 用户点击了"打开"按钮For Each selectedFile In .SelectedItemsMsgBox selectedFileNext selectedFileEnd IfEnd WithSet fileDialog = NothingEnd Sub```- 使用FileSystemObject对象获取文件路径另一种获取特定文件的路径的方法是使用VBA中的FileSystemObject对象。
VBA中目录操作的实用技巧VBA(Visual Basic for Applications)是一种用于自动化任务的编程语言,它被广泛应用于Microsoft Office套件中的各种应用程序,如Excel、Word和PowerPoint。
在这些应用程序中,目录操作是开发人员经常需要处理的任务之一。
本文将介绍几个VBA中目录操作的实用技巧,帮助您更好地处理和管理文件目录。
1. 查找文件夹和文件在VBA中,可以使用FileSystemObject对象来执行与文件和文件夹有关的操作。
要查找特定文件夹中的文件,您可以使用以下代码:```Sub FindFilesInFolder()Dim FileSystem As ObjectDim Folder As ObjectDim File As ObjectSet FileSystem = CreateObject("Scripting.FileSystemObject")Set Folder = FileSystem.GetFolder("C:\目录路径")'循环遍历文件夹中的文件For Each File In Folder.Files'处理文件操作Next FileEnd Sub```在上述代码中,“C:\目录路径”是您要查找的文件夹的路径。
通过循环遍历文件夹中的文件,您可以对每个文件执行特定的操作,如复制、移动或重命名。
如果您要查找特定文件夹中的特定文件,可以将上述代码中的循环遍历修改为以下代码:```For Each File In Folder.FilesIf Like "*.txt" Then '查找扩展名为txt的文件'处理文件操作End IfNext File```在上述代码中,使用了通配符“*”来匹配文件名中的任意字符,并且使用“Like”关键字来比较文件名与模式是否匹配。
VBA7种⽂档遍历法Sub 在选定⽂档最后加⼊⼀句话() '遍历⽂件Dim MyDialog As FileDialogOn Error Resume NextApplication.ScreenUpdating = FalseSet MyDialog = Application.FileDialog(msoFileDialogFilePicker)With MyDialog' .InitialFileName = "C:\".Filters.Clear '清除所有⽂件筛选器中的项⽬.Filters.Add "所有 WORD ⽂件", "*.doc", 1 '增加筛选器的项⽬为所有WORD⽂件.AllowMultiSelect = True '允许多项选择If .Show = -1 Then '确定For Each i In .SelectedItems '在所有选取项⽬中循环With Documents.Open(i, , , , , , , , , , , False).Range.InsertAfter Chr$(13) & "改成你想加⼊的话................".Close TrueEnd WithNextEnd IfEnd WithApplication.ScreenUpdating = TrueEnd SubSub简单遍历测试()For Each F In Dir遍历'Office2003遍历,FSO遍历,双字典遍历,CMD遍历,栈遍历,管道遍历,Dir遍历'此处加⼊⽂件处理代码即可。
Selection.InsertAfter F & Chr(13)i = i + 1NextSelection.InsertAfter iMsgBox"OKOK", vbOKOnly, "OKKO"End SubSub单个⽂档处理(F)Dim pa As Paragraph, c As RangeWith Documents.Open(F, Visible:=False)For Each pa In .ParagraphsFor Each c In pa.Range.CharactersIf = "仿宋"And Abs(Asc(c)) > 128Then = "仿宋_GB2312"ElseIf = "仿宋"And Abs(Asc(c)) < 128Then = "Times New Roman"End IfNextNext.Close TrueEnd WithEnd Sub' 遍历⽂件夹Function CMD遍历()Dim arrDim t: t = TimerWith Application.FileDialog(msoFileDialogFolderPicker)' .InitialFileName = "D:\" '若不加这句则打开上次的位置If .Show <> -1Then Exit Functionfod = .InitialFileNameEnd WithCMD遍历⽂件 arr, fod, "*.doc*"arr = Filter(arr, "*", False, vbTextCompare)CMD遍历 = arrEnd FunctionFunction栈遍历()Dim arr() As StringDim t: t = TimerWith Application.FileDialog(msoFileDialogFolderPicker)If .Show <> -1Then Exit Functionfod = .InitialFileNameEnd With遍历栈 arr, CStr(fod), "doc*", True'这种⽅式就不⽤使⽤Function在函数中返回了栈遍历 = arrEnd FunctionFunction管道遍历()Dim t: t = TimerDim a As New DosCMDDim arrWith Application.FileDialog(msoFileDialogFolderPicker)If .Show <> -1Then Exit Functionfod = .InitialFileNameEnd Witha.DosInput Environ$("comspec") & " /c dir " & Chr(34) & fod & "\*.doc*" & Chr(34) & " /s /b /a:-d"arr = a.DosOutPutEx '默认等待时间120sarr = Split(arr, vbCrLf) '分割成数组arr = Filter(arr, ".doc", True, vbTextCompare) '仅保留doc⽂件arr = Filter(arr, "*", False, vbTextCompare)arr = Filter(arr, "$", False, vbTextCompare)管道遍历 = arr'For Each F In arr' If InStr(F, "$") = 0 And F <> "" Then' Debug.Print F' '单个⽂档处理代码 (F)'------------------------------------------------------------------------------★★★★★★★★★★★★★★★' End If'Next'MsgBox "已完成!!!", vbOKCancel, "代码处理"End FunctionFunction AllName() '遍历获得⽂件名,交给数组,不变的部分;'选定的所有word⽂档With Application.FileDialog(msoFileDialogFilePicker).Filters.Add "选择03版word⽂档", "*.doc", 1.Filters.Add "所有⽂件", "*.*", 2If .Show <> -1Then Exit FunctionFor Each F In .SelectedItemsIf InStr(F, "$") = 0Thenstr0 = str0 & F & Chr(13)End IfNextEnd WithAllName = Left(str0, Len(str0) - 1)End FunctionFunction AllFodName() '⽤dos命令遍历选定⽂件夹下的所有word⽂档Dim fso As ObjectDim aCollection As New CollectionSet fso = CreateObject("scripting.filesystemobject")With Application.FileDialog(msoFileDialogFolderPicker).Title = "选择⽂档所在⽂件夹"If .Show <> -1Then Exit Functionfolder = .SelectedItems(1)End WithSet ws = CreateObject("WScript.Shell")' ws.Run Environ$("comspec") & " /c dir " & folder & "\*.ppt /s /a:-d /b/on|find /v" & Chr(34) & ".pptx" & Chr(34) & "> C:\temp.txt", 0, True ws.Run Environ$("comspec") & " /c dir " & Chr(34) & folder & Chr(34) & "\*.doc* /s /a:-d /b/on" & "> C:\temp.txt", 0, TrueOpen "C:\temp.txt"For Input As #1arr = Split(StrConv(InputB(LOF(1), 1), vbUnicode), vbCrLf)Close #1ws.Run Environ$("comspec") & " /c del /q /s " & Chr(34) & "C:\temp.txt" & Chr(34), 0, False'删除临时⽂件Set ws = Nothing' '--------------------------此处是否多此⼀举?-----------------------' For i = LBound(arr) To UBound(arr) - 1 '使⽤集合提⾼效率' aCollection.Add arr(i)' Next' '--------------------------------------------------------------------' For i = 0 To UBound(arr)'' aname = CreateObject("Scripting.FileSystemObject").GetBaseName(arr(i))'' If InStr(1, aname, "$") = 0 Then' If InStr(1, arr(i), "$") = 0 Then Debug.Print arr(i)' Selection.InsertAfter arr(i)'' End If' NextAllFodName = arrEnd FunctionFunction FSO遍历() '我的得意代码之⼗五⽂档不引⽤'*------------------------------------------------------------------------------*Dim fso As Object, b As Object, arr() As String, F '注意,这⾥的as string是必须,否则,filter函数⽆法使⽤。
VBA遍历所有文件夹的两种方法(filesearch和FileSystemObject)
在VBA遍历文件夹和子文件夹中所有文件,常用两种方法,一种是使用VBA的filesercth对象,另外一种是使用FileSystemObject(windows文件管理工具)和递归方法。
兰色对代码进行了注解,希望对大家有所帮助
第一种方法:使用filesearch对象
Sub mysearch()
Dim fs, i, arr(1 To 10000)
Set fs = Application.FileSearch '设置一个搜索对象
With fs
.LookIn = ThisWorkbook.Path & "/" '设置搜索路径
.Filename = "*.xls" '要搜索文件名和类型
.SearchSubFolders = True '是否需要搜索子文件夹
If .Execute > 0 Then '如果找不到文件
MsgBox "There were " & .FoundFiles.Count & _
" file(s) found." '显示文件找不到
For i = 1 To .FoundFiles.Count '通过循环把所有搜索到的文件存入到数组中
arr(i) = .FoundFiles(i)
Next i
Sheets(1).Range("A1").Resize(.FoundFiles.Count) = Application.Transpose(arr) ' '把数组内的路径和文件名放在单元格中
Else
MsgBox "There were no files found."
End If
End With
End Sub
第二种方法:引用FileSystemObject对象
注意:要使用FileSystemObject对象,需要首先引用一下,具体方法,VBE--工具--引用--找到miscrosoft scription runtime项目并选中
代码及注释:
Dim ArrFiles(1 To 10000) '创建一个数组空间,用来存放文件名称
Dim cntFiles% '文件个数
Public Sub ListAllFiles()
Dim strPath$ '声明文件路径
Dim i%
'Set fso = CreateObject("Scripting.FileSystemObject")
Dim fso As New FileSystemObject, fd As Folder '创建一个FileSystemObject对象和一个文件夹对象
strPath = ThisWorkbook.Path & "/" '"设置要遍历的文件夹目录
cntFiles = 0
Set fd = fso.GetFolder(strPath) '设置fd文件夹对象
SearchFiles fd '调用子程序查搜索文件
Sheets(1).Range("A1").Resize(cntFiles) = Application.Transpose(ArrFiles) '把数组内的路径和文件名放在单元格中
End Sub
Sub SearchFiles(ByVal fd As Folder)
Dim fl As File
Dim sfd As Folder
For Each fl In fd.Files '通过循环把文件逐个放在数组内
cntFiles = cntFiles + 1
ArrFiles(cntFiles) = fl.Path
Next fl
If fd.SubFolders.Count = 0 Then Exit Sub 'SubFolders返回由指定文件夹中所有子文件夹(包括隐藏文件夹和系统文件夹)组成的Folders 集合
For Each sfd In fd.SubFolders '在Folders 集合进行循环查找
SearchFiles sfd '使用递归方法查找下一个文件夹
Next
End Sub。