VBA循环遍历子文件夹中的文件

时间:2015-02-20 12:53:53

标签: excel vba excel-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

3 个答案:

答案 0 :(得分:2)

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

我测试了它,它的功能就像魅力一样:

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

答案 1 :(得分:1)

  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

答案 2 :(得分:1)

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