Forum Discussion
Tarek3
Oct 21, 2022Copper Contributor
Help with macro to export ONLY the first sheet of multiple excel workbooks to PDFs
Hi All! I have been working to clean up this macro code to allow it to run better on my computer. To preface, I have really little knowledge about all this, and have had a variety of people contribut...
HansVogelaar
Oct 21, 2022MVP
Perhaps it's a timing problem. Does it work if you add a couple of DoEvents lines in the loop?
'Loop until all found
Do Until fName = ""
Set wbSource = Workbooks.Open(fPath & fName)
DoEvents
'This is the part that may need to be changed
With wbSource
sFile = .Worksheets(1).Name & ".pdf"
.Worksheets(1).ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=sPath & sFile, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=False, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
End With
DoEvents
wbSource.Close SaveChanges:=False
'Get name of next file
fName = Dir()
LoopTarek3
Oct 21, 2022Copper Contributor
Thank you for your response! Where would it be effective to add DoEvents? I'm unfamiliar with that.
Thank you!
Thank you!
- HansVogelaarOct 21, 2022MVP
See my first reply - I posted a version of the loop with 2 DoEvents inserted.
- Tarek3Oct 21, 2022Copper Contributor
Thank you, I added your suggested changes, and unfortunately arrived at the same issue shown in the images linked in the original post, and just one pdf produced. By chance, do you have any additional suggestions to edit the code?
Below is the code I just tried to run (with the suggested edits).Sub Printer() Dim sFile As String Dim sPath As String Dim wks As Worksheet Dim wbSource As Workbook Dim fPath As String Dim fName As String 'What folder to search? fPath = "C:\Users\User1\Desktop\PDF_Test" 'Where will we save to? sPath = "C:\Users\User1\Desktop\PDF_Test\To_Save" 'Error check If Right(fPath, 1) <> Application.PathSeparator Then fPath = fPath & Application.PathSeparator End If If Right(sPath, 1) <> Application.PathSeparator Then sPath = sPath & Application.PathSeparator End If MsgBox "We are looking in: " & fPath MsgBox "Files will save to: " & sPath 'Find files fName = Dir(fPath & "*.xls*") MsgBox "Attempt at first file name: " & fName 'Run faster Application.ScreenUpdating = False 'Loop until all found Do Until fName = "" Set wbSource = Workbooks.Open(fPath & fName) DoEvents 'This is the part that may need to be changed With wbSource sFile = .Worksheets(1).Name & ".pdf" .Worksheets(1).ExportAsFixedFormat Type:=xlTypePDF, _ Filename:=sPath & sFile, _ Quality:=xlQualityStandard, _ IncludeDocProperties:=False, _ IgnorePrintAreas:=False, _ OpenAfterPublish:=False End With DoEvents wbSource.Close SaveChanges:=False 'Get name of next file fName = Dir() Loop Application.ScreenUpdating = True End Sub
Thank you again!- HansVogelaarOct 21, 2022MVP
Sorry, no idea what causes the problem.