【发布时间】:2017-09-01 15:25:22
【问题描述】:
我想遍历一个文件夹 (G:/Proj) 并找到任何名为“SUMMARY LOG”的子文件夹,然后在每个文件夹中打印 Excel 文件,通常只有一个。
每个项目都有一个 Summary LOG 文件夹。
这是 VBA 代码。它遍历每个子文件夹并打印出这些文件夹中的每个 Excel 文件,而不仅仅是“SUMMARY LOG”。
Sub LoopFolders()
Dim strFolder As String
Dim strSubFolder As String
Dim strFile As String
Dim colSubFolders As New Collection
Dim varItem As Variant
Dim wbk As Workbook
' Parent folder including trailing backslash
strFolder = "G:/Proj/"
' Loop through the subfolders and fill Collection object
strSubFolder = Dir(strFolder & "*", vbDirectory)
Do While Not strSubFolder = ""
Select Case strSubFolder
Case ".", ".."
' Current folder or parent folder - ignore
Case Else
' Add to collection
colSubFolders.Add Item:=strSubFolder, Key:=strSubFolder
End Select
' On to the next one
strSubFolder = Dir
Loop
' Loop through the collection
For Each varItem In colSubFolders
' Loop through Excel workbooks in subfolder
strFile = Dir(strFolder & varItem & "\*.xls*")
Do While strFile <> ""
' Open workbook
Set wbk = Workbooks.Open(Filename:=strFolder & _
varItem & "\" & strFile, AddToMRU:=False)
' Do something with the workbook
ActiveSheet.PrintOut
' Close it
wbk.Close SaveChanges:=False
strFile = Dir
Loop
Next varItem
End Sub
【问题讨论】:
-
strFile = Dir(strFolder & varItem & "\SUMMARY LOG\*.xls*")