VBA循环访问子文件夹中的文件

我需要修改多个Excel文件中的列标题。 这些文件位于我要循环访问的文件夹的两个级别的子文件夹中(每个文件夹中有28个.xlsx文件,每个期间有一个文件夹)。

文件结构是:“c:\ … filepath … \ Period * \ Daily Attributions \ *。xlsx”

我已经设法得到一些代码工作,循环通过文件夹中的每个文件,但我需要帮助重复每个文件夹中的所有文件相同的循环。

这是我迄今为止。

Sub FirstLast() ' ' FirstLast Macro ' Dim sPath As String Dim sFile As String Dim wb As Workbook sPath = "C:\...filepath...\Period 1\Daily Attributions\" sFile = Dir(sPath & "*.xlsx") Do While sFile <> "" Set wb = Workbooks.Open(sPath & sFile, UpdateLinks:=False) Range("E1").Select ActiveCell.FormulaR1C1 = "FirstLast" ActiveWorkbook.Save ActiveWindow.Close sFile = Dir Loop End Sub 

这个答案就是我上面评论的例子:

我已经testing过它,它的作用就像魅力:

 Sub FirstLast() Dim sPath As String Dim sFile As String Dim wb As Workbook Dim subfolder As String Dim subdir As Collection Set subdir = New Collection Dim maindir As String: maindir = "D:\main\" 'Above line is the main directory which is "C:\...filepath...\" subfolder = Dir(maindir, vbDirectory) Do While subfolder <> "" subdir.Add Item:=subfolder subfolder = Dir(, vbDirectory) Loop ' remove . and .. subdir.Remove (1) subdir.Remove (1) For Each m In subdir sPath = maindir & "\" & m & "\Daily Attributes" sFile = Dir(sPath & "*.xlsx") Do While sFile <> "" ' do stuff: 'Set wb = Workbooks.Open(sPath & sFile, UpdateLinks:=False) 'Range("E1").Select 'ActiveCell.FormulaR1C1 = "FirstLast" 'ActiveWorkbook.Save 'ActiveWindow.Close sFile = Dir Loop Next End Sub 
  Sub FirstLast() ' ' FirstLast Macro ' Dim sPath As String Dim sFile As String Dim wb As Workbook sPath = "C:\...filepath...\Period 1\Daily Attributions\" sFile = Dir(sPath & "*.xlsx") for i = 1 to 3 'pseudo code '"open foldername " & i 'looping through files in folder Do While sFile <> "" Set wb = Workbooks.Open(sPath & sFile, UpdateLinks:=False) Range("E1").Select ActiveCell.FormulaR1C1 = "FirstLast" ActiveWorkbook.Save ActiveWindow.Close sFile = Dir Loop next i End Sub 
 Sub M_snb() sn=split(createobject("wscript.shell").exec("cmd /c Dir ""C:\...filepath...\Period *\Daily Attributions\*.xls"" /b /s").stdout.readall,vbcrlf) for j=0 to ubound(sn) with getobject(sn(j)) .sheets(1).cells(1,5)="firstlast" .close -1 end with next end sub