Need to modify my VBA code to include subfolders a

2019-09-22 03:23发布

I have created a VBA code that loops through all excel workbooks in a given folder , opens then, refreshes the sheet, pauses for 10 seconds, closes and saves and moves on to the next. The issue I am facing is that it wont do it for the excel workbooks in the subfolder, Please can someone assist.

The code is as per below:

Sub LoopAllExcelFilesInFolder()
'PURPOSE: To loop through all Excel files in a user specified folder and perform a set task on them
'SOURCE: www.TheSpreadsheetGuru.com

Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog

'Optimize Macro Speed
  Application.ScreenUpdating = False
  Application.EnableEvents = False
  Application.Calculation = xlCalculationManual

'Retrieve Target Folder Path From User
  Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)

    With FldrPicker
      .Title = "Select A Target Folder"
      .AllowMultiSelect = False
        If .Show <> -1 Then GoTo NextCode
        myPath = .SelectedItems(1) & "\"
    End With

'In Case of Cancel
NextCode:
  myPath = myPath
  If myPath = "" Then GoTo ResetSettings

'Target File Extension (must include wildcard "*")
  myExtension = "*.xls*"

'Target Path with Ending Extention
  myFile = Dir(myPath & myExtension)

'Loop through each Excel file in folder
  Do While myFile <> ""
    'Set variable equal to opened workbook
      Set wb = Workbooks.Open(Filename:=myPath & myFile)

    'Ensure Workbook has opened before moving on to next line of code
      DoEvents

    'Change First Worksheet's Background Fill Blue
      Application.Calculate
      ActiveWorkbook.RefreshAll
  Application.Wait (Now + TimeValue("0:00:10"))

    'Save and Close Workbook
      wb.Close SaveChanges:=True

    'Ensure Workbook has closed before moving on to next line of code
      DoEvents

    'Get next file name
      myFile = Dir
  Loop

'Message Box when tasks are completed
  MsgBox "Task Complete!"

ResetSettings:
  'Reset Macro Optimization Settings
    Application.EnableEvents = True
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True

End Sub

1条回答
一夜七次
2楼-- · 2019-09-22 03:49

Its probably an old question indeed, but still, I enjoyed writing it somehow. And in my solution, you get some nice printing in the console. Here you go:

Option Explicit

Function GetFiles(ByVal Folder As String) As Collection

    Dim strFile As String

    Set GetFiles = New Collection
    strFile = Dir(Folder & "\*")

    Do While strFile <> ""
        GetFiles.Add strFile
        strFile = Dir
    Loop

End Function

Function GetFolders(ByVal Folder As String) As Collection

    Dim strFile As String
    Set GetFolders = New Collection

    strFile = Dir(Folder & "\*", vbDirectory)

    Do While strFile <> ""
        If GetAttr(Folder & "\" & strFile) And vbDirectory Then GetFolders.Add strFile
        strFile = Dir
    Loop

End Function

Sub LoopThroughSubfoldersAsWell()

    Dim colFoFi     As Collection
    Dim varEl01     As Variant
    Dim varEl02     As Variant
    Dim varEl03     As Variant
    Dim strLine     As String: strLine = "--------------------------"

    Dim strAddress As String: strAddress = "C:\Users\UserName\Desktop\Testing01\"

    Debug.Print strAddress
    Set colFoFi = GetFiles(strAddress)

    For Each varEl01 In colFoFi
        Debug.Print varEl01
    Next varEl01
    Debug.Print strLine

    Set colFoFi = GetFolders(strAddress)
    For Each varEl01 In colFoFi
        If Len(varEl01) > 2 Then  'to avoid some hidden stuff

            Set varEl02 = GetFiles(strAddress & varEl01)
            Debug.Print (strAddress & varEl01)

            For Each varEl03 In varEl02
                Debug.Print varEl03
            Next varEl03

            Debug.Print strLine

        End If
    Next varEl01

End Sub
查看更多
登录 后发表回答