Learn

Macro 13: Print All Workbooks in a Directory

Macro 13: Print All Workbooks in a Directory

If you need to print from multiple workbooks in a directory, you can use this macro.

How it works

In this macro, we use the Dir function to return a string that represents the name of the file that

matches what you pass to it.

In this code, we use the Dir function to enumerate through all the .xlsx files in a given directory,

capturing each file’s name. Then we open each file, print, and close the file.

Sub Macro13()

‘Step 1:Declare your variables

Dim MyFiles As String

‘Step 2: Specify a target directory

MyFiles = Dir(“C:\Temp\*.xlsx”)

Do While MyFiles <> “”

‘Step 3: Open Workbooks one by one

Workbooks.Open “C:\Temp\” & MyFiles

ActiveWorkbook.Sheets(“Sheet1”).PrintOut Copies:=1

ActiveWorkbook.Close SaveChanges:=False

‘Step 4: Next File in the Directory

MyFiles = Dir

Loop

End Sub

1. Step 1 declares the MyFiles string variable that will capture each filename that is in the

enumeration.

2. Step 2 uses the Dir function to specify the directory 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 filename 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 proba-

bly 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.

How to use it

To implement this macro, you can copy and paste it 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 InsertModule.

4. Type or paste the code in the newly created module, modifying the print statement as

needed.

learn
We will be happy to hear your thoughts

Leave a reply

Share knowledge
Learn
Logo
Enable registration in settings - general