Skip to main content

Excel Macro: Print All Workbooks in a Folder

Sometimes you may need to print all workbooks in a folder, open each workbook, print, close the workbook, and then open the next one. Opening and printing each workbook in a folder is typically a time consuming manual process. This little macro takes care of that annoyance.

Print All Workbooks in a Folder

'---------------- Modules ----------------
Sub PrintAllWorkbooks()
    'Step 1:Declare your variables
    Dim MyFiles As String
    'Step 2: Specify a target folder/directory
    MyFiles = Dir("D:\Temp\*.xlsx")
    Do While MyFiles <> ""
        'Step 3: Open Workbooks one by one
        Workbooks.Open "D:\Temp\" & MyFiles
        ActiveWorkbook.Sheets("Sheet1").PrintOut Copies:=1
        ActiveWorkbook.Close SaveChanges:=False
        'Step 4: Next File in the Directory
        MyFiles = Dir
    Loop
End Sub

How This Macro Works

In this code, we use the Dir function to enumerate through all the .xlsx files in a given folder, capturing each file’s name. Then we open each file, print, and close the file.

  1. Step 1 declares the MyFiles string variable that will capture each file name that is in the enumeration.
  2. Step 2 uses the Dir function to specify the folder and file type we are looking for. Note that the code here is looking for *.xlsx. This means that only .xlsx files will be looped through. If you are looking for .xls files, you will need to specify that (along with the directory you need to search). The macro passes any file name it finds to the MyFiles string variable.
  3. Step 3 opens the file and then prints out one copy of Sheet1. Needless to say, you will probably want to change which sheets to print. You can also change the number of copies to print.
  4. Step 4 loops back to find more files. If there are no more files, the MyFiles variable is blank. If that is the case, the loop and macro end.

Most VBA code should be placed in Standard Modules unless specified.

If you see a comment '------------------ Modules------------------ in the code header that means put the code in a Standard Module. For more information, learn this course: Where should I put the Excel VBA code?

The following steps teach you how to put VBA code into a Standard Module:

  1. Activate the Visual Basic Editor by pressing ALT + F11.
  2. Right-click the project/workbook name in the Project Window.
  3. Choose Insert -> Module.
  4. Type or paste the code in the newly created module. You will probably need to change the sheet name, the range address, and the save location.
  5. Click Run button on the Visual Basic Editor toolbar.
  6. For more information, learn this course: Programming with Excel VBA

Leave a comment

Your email address will not be published. Required fields are marked *

Format your code: <pre><code class="language-vba">place your code here</code></pre>