我有一些excel(.xls)存储在本地驱动器的文件夹中。我需要对此文件夹中的每个文件执行一些处理。
的代码是什么?为了更清楚,我想要遍历每个文件并对其进行处理。完成文件后,转到另一个文件,直到文件夹中的所有文件结束。我确实有处理代码;我只需要知道将遍历文件然后移动到另一个文件夹的代码。
提前感谢您的帮助,
答案 0 :(得分:1)
您需要的是一个递归函数,它迭代表示文件系统的树。这意味着迭代某些“父文件夹”的所有子节点。我发给你一个功能类似于你需要的功能(目前正在使用中)。此函数删除给定父文件夹的所有空文件夹。
Public Function gf_DeleteEmptyFolder(path As String) As Boolean
On Error GoTo Error_Handler
Dim fso_folder As Scripting.Folder, sub_folder As Scripting.Folder
If g_FSO.FolderExists(path) Then
Set fso_folder = g_FSO.GetFolder(path)
'-- eliminates de folder only if is empty
If 0 = fso_folder.Files.Count And 0 = fso_folder.SubFolders.Count Then
Call g_FSO.DeleteFolder(path, False)
'-- recursively calls the function
Else
For Each sub_folder In fso_folder.SubFolders
Call gf_DeleteEmptyFolder(sub_folder.path)
Next
End If
End If
gf_DeleteEmptyFolder = True
Exit Function
'~~~ on error
Error_Handler:
gf_DeleteEmptyFolder = False
End Function
如果您的文件存储在一个简单的文件夹中,那么您可以使用以下代码来迭代每个文件。
Public Sub fsoProcessFilesInFolder(sFolder As String)
Dim fso As Scripting.FileSystemObject, fld As Scripting.Folder, fil As Scripting.File
Set fso = New FileSystemObject
Set fld = fso.GetFolder(sFolder)
For Each fil In fld.Files
'--- add code to process your files
Next fil
End Sub
答案 1 :(得分:1)
这是简单的VBA对象方式:
Dim fs As FileSearch
Dim i As Integer
Dim wbk As Workbook
Set fs = Application.FileSearch
With fs
.LookIn = ThisWorkbook.Path
.FileName = "*.xls"
For i = 1 to .Execute()
Set wbk = Workbooks.Open(.FoundFiles(i))
''//DO STUFF HERE
wbk.Close(SaveChanges:=True)
Next i
End With
在VB6中,您有三个选项,如以下知识库文章所示:
How to Search Directories to Find or List Files
HOW TO: Recursively Search Directories by Using FileSystemObject
答案 2 :(得分:0)
以下代码将从给定文件夹中读取xlsx / xls文件,忽略其他文件并遍历每个项目。 您可以将它用于任何扩展和过滤器集。
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(folderPath)
Set objFiles = objFolder.Files
'Iterate through the files in the folder
For Each Item In objFiles
If LCase(Right(Item.Name, 5)) = ".xls" Or LCase(Right(Item.Name, 4)) = ".xlsx" Then
''''''Do Stuffs Here''''''
End If
Next