对文件夹中的所有子文件夹执行相同的操作

下面的代码将“C:\ Files \ Bangalore”中的所有xlsx文件转换为csv文件。

Sub xlsxTOcsv() Dim sPathInp As String Dim sPathOut As String Dim sFile As String sPathInp = "C:\Files\Bangalore\" sPathOut = "C:\Files\Bangalore" Application.DisplayAlerts = False sFile = Dir(sPathInp & "*.xlsx") Do While Len(sFile) With Workbooks.Open(fileName:=sPathInp & sFile) .SaveAs fileName:=sPathOut & Left(.Name, InStr(1, .Name, ".") - 1), _ fileformat:=xlCSV, _ CreateBackup:=False .Close SaveChanges:=False End With sFile = Dir() Loop Kill sPathInp & "\" & "*.xlsx" End Sub 

问题是我有很多类似的文件夹在我的“C:\ Files \”为不同的城市。

例如:

C:\文件\奈
C:\文件\德里
C:\文件\加尔各答
C:\文件\孟买

等等

我正在所有这些文件夹中执行相同的操作。

有没有办法通过调用“C:\ Files \”对所有这些子文件夹执行相同的操作?

我没有“C:\ Files \”中的任何文件,只有子文件夹。

这是一个通用的解决scheme,您不需要知道子文件夹的名称。 这将find所有的子文件夹,并在每个文件夹中处理电子表格。

您需要通过单击工具菜单,引用…来引用Windows Script Host Object Model ,然后向下滚动并勾选Windows Script Host Object Model

 Sub xlsxTOcsv() Dim sPathInp As String Dim sPathOut As String Dim sFile As String Dim rootFolderPath As String Dim rootFolder As Folder Dim subFolder As Folder rootFolderPath = "C:\Files" ''You need to add a reference to Windows Script Host Object Model Dim fso As New FileSystemObject Application.DisplayAlerts = False Set rootFolder = fso.GetFolder(rootFolderPath) For Each subFolder In rootFolder.SubFolders sPathInp = subFolder.Path & "\" sPathOut = sPathInp sFile = Dir(sPathInp & "*.xlsx") Do While Len(sFile) With Workbooks.Open(Filename:=sPathInp & sFile) .SaveAs Filename:=sPathOut & Left(.Name, InStr(1, .Name, ".") - 1), _ FileFormat:=xlCSV, _ CreateBackup:=False .Close SaveChanges:=False End With sFile = Dir() Loop Kill sPathInp & "*.xlsx" Next subFolder Application.DisplayAlerts = True End Sub 

你可以将它们添加到一个简单的数组中并循环:

 Sub xlsxTOcsv() Dim sPathInp As String Dim sPathOut As String Dim sFile As String Dim vArr Dim vFile vArr = Array("Bangalore", "Chennai", "Delhi", "Kolkata") sPathInp = "C:\Files\" sPathOut = "C:\Files\" Application.DisplayAlerts = False For Each vFile In vArr sFile = Dir(sPathInp & vFile & "\*.xlsx") Do While Len(sFile) With Workbooks.Open(Filename:=sPathInp & vFile & "\" & sFile) .SaveAs Filename:=sPathOut & vFile & "\" & Left$(.Name, InStr(1, .Name, ".") - 1), _ FileFormat:=xlCSV, _ CreateBackup:=False .Close SaveChanges:=False End With sFile = Dir() Loop Kill sPathInp & vFile & "\" & "*.xlsx" Next Application.DisplayAlerts = True End Sub