Trying to print excel files from specific folder names with Macro

mweigle2

New Member
Joined
Aug 31, 2017
Messages
1
Below is a Macro that I have taken and "attempted" to modify to what exactly as I want. I feel that I am very close and am just missing one or two things , however I am not too familiar with macros or VB for that matter. My end goal with this macro is to go through the directory listed above ( G:/Proj) and print only the excel files in the sub folders named "Summary Log". This macro right now however goes through and prints every single excel file in every single sub folder. Any ideas on how I can trim the results just to print the ones under the File names "Summary Log"?

Thanks


Code:
[/FONT][/COLOR]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
[COLOR=#000000][FONT=Verdana]
 

Excel Facts

Can a formula spear through sheets?
Use =SUM(January:December!E7) to sum E7 on all of the sheets from January through December
Try this. Place all code in a standard module.

Code:
Option Explicit

Public varFileArray() As Variant
Sub Call_ListFilesInFolder()

    Dim sWorksheet As String
    Dim lRowCount As Long
    
    'Reset Output Worksheet
    sWorksheet = "Files to Print"
    On Error Resume Next
    Application.DisplayAlerts = False
    Worksheets(sWorksheet).Delete
    Application.DisplayAlerts = True
    On Error GoTo 0
    Worksheets.Add(after:=Sheets(Sheets.Count)).Name = sWorksheet 'After last
    Worksheets(sWorksheet).Range("A1").Resize(1, 5).Value = Array("File Name Ext", "Path", "Created", "Modified", "Accessed")
    
    'Create Array of Files to Print (see info in CreateFilesArray module on arguments for this sub)
    CreateFilesArray "G:\Proj", "Summary Log", "*.xls*", True
    
    'Copy Array to Output Worksheet
    lRowCount = UBound(varFileArray, 2)
    With Worksheets(sWorksheet)
        .Range("A2").Resize(lRowCount, 5).Value = Application.Transpose(varFileArray)
    End With
    
    'Option to Print all files
    Select Case MsgBox("There are " & UBound(varFileArray, 2) & " files to be printed.  " & vbLf & vbLf & _
        "They are listed on the 'Files to Print' worksheet." & vbLf & vbLf & _
        "Do you want to print them now?", vbYesNo, "Print Files?")
    Case vbYes
        PrintFilesOnOutputWorksheet
    Case Else
        MsgBox "Print Cancelled"
    End Select
    
End Sub

Sub PrintFilesOnOutputWorksheet()

    Dim sFilePathNameExt As String
    Dim lRowIndex As Long
    Dim lLastRow As Long
    Dim wbk As Workbook
    Dim secAutomation As MsoAutomationSecurity
    
    secAutomation = Application.AutomationSecurity                          'Save ThisWorkbook security setting
    Application.AutomationSecurity = msoAutomationSecurityForceDisable      'Disable macros when opening file

    With Worksheets("Files to Print")
        lLastRow = .Cells(.Rows.Count, 1).End(xlUp).Row
        For lRowIndex = 2 To lLastRow
            sFilePathNameExt = .Cells(lRowIndex, 2).Value & .Cells(lRowIndex, 1).Value
            ' Open workbook
            Set wbk = Workbooks.Open(Filename:=sFilePathNameExt, AddToMRU:=False, ReadOnly:=True)
            ' Do something with the workbook
            'ActiveSheet.PrintOut
            Debug.Print .Cells(lRowIndex, 1).Value & ", ",
            ' Close it
            wbk.Close SaveChanges:=False
        Next
    End With
    Set wbk = Nothing
    Application.AutomationSecurity = secAutomation                          'Restore ThisWorkbook security setting
    
End Sub

Function CreateFilesArray(sSourceFolderName As String, sTargetSubfolder As String, sFilePattern As String, bIncludeSubfolders As Boolean) As Variant
    'sSourceFolderName  Folder to start search in
    'sTargetSubfolder   Name of the subfolder(s) that contain the file(s) to be printed
    '                   There may be multiple subfolders with this name. Files with this name in their path will be print candiates
    'sFilePattern       If a print candidate FileNameExt matches this pattern then it will be printed
    'bIncludeSubfolders True if folders under the sSourceFolderName folder should be searched
    '                   False to search only the sSourceFolderName folder
    
    Dim FSO As Object
    Set FSO = CreateObject("Scripting.FileSystemObject")
    
    Dim SourceFolder As Object
    
    If LenB(sTargetSubfolder) = 0 Then sTargetSubfolder = "*"
    
    Dim SubFolder As Object
    Set SubFolder = FSO.GetFolder(sSourceFolderName)
    
    Dim FileItem As Object
    
    Dim lMatchingFileCount As Long
    Dim lFileCount As Long
    
    Set SourceFolder = FSO.GetFolder(sSourceFolderName)
    
    lFileCount = 0
    On Error Resume Next
    lMatchingFileCount = UBound(varFileArray, 2)
    If Err.Number <> 0 Then lMatchingFileCount = 0
    On Error GoTo 0
    
    If InStr(SourceFolder.Path & "\", "\" & sTargetSubfolder & "\") > 0 Then
        Debug.Print SourceFolder.Path & "\"
    
        For Each FileItem In SourceFolder.Files
            lFileCount = lFileCount + 1
            ' display file properties
            'Debug.Print FileItem.Name
            If FileItem.Name Like sFilePattern Then
                lMatchingFileCount = lMatchingFileCount + 1 ' next row number
                ReDim Preserve varFileArray(1 To 5, 1 To lMatchingFileCount)
                varFileArray(1, lMatchingFileCount) = FileItem.Name
                varFileArray(2, lMatchingFileCount) = Left(FileItem.Path, InStrRev(FileItem.Path, "\"))
                varFileArray(3, lMatchingFileCount) = FileItem.DateCreated
                varFileArray(4, lMatchingFileCount) = FileItem.DateLastModified
                varFileArray(5, lMatchingFileCount) = FileItem.DateLastAccessed
            End If
        Next FileItem
        'Debug.Print lFileCount, lMatchingFileCount, SourceFolder.Name
    End If
    
    If bIncludeSubfolders Then
        For Each SubFolder In SourceFolder.SubFolders
            CreateFilesArray SubFolder.Path, sTargetSubfolder, sFilePattern, True
        Next SubFolder
    End If
    
    Set FileItem = Nothing
    Set SourceFolder = Nothing
    Set FSO = Nothing

End Function
 
Upvote 0

Forum statistics

Threads
1,216,474
Messages
6,130,841
Members
449,598
Latest member
sunny_ksy

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top