Code to append to an existing PDF or rename

Obsidian

New Member
Joined
Aug 10, 2006
Messages
19
Hi, I am using the VBA code below to export to PDF, and saving as the sheet name. Unfortunately, when I come across the same sheet name (from a different workbook) it overwrites the existing PDF.

I would ideally like to append to the existing PDF instead of overwriting. If that is not possible, then even renaming the 2nd, 3rd, etc with a 1, 2 3 at the end (or something similar) would be great. Thanks for the help.

Code:
Sub ExportToPDFs()
Dim ws As Worksheet


For Each ws In Worksheets
ws.Select
nm = ws.Name


ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:="C:\Users\X\Documents\" & nm & ".pdf", _
Quality:=xlQualityStandard, IncludeDocProperties:=True, _
IgnorePrintAreas:=False, OpenAfterPublish:=False


Next ws


End Sub
 

Excel Facts

Can you AutoAverage in Excel?
There is a drop-down next to the AutoSum symbol. Open the drop-down to choose AVERAGE, COUNT, MAX, or MIN
Try this:
Code:
Sub ExportToPDFs()
    Dim ws As Worksheet
    Dim i As Integer
    Dim dirPath As String, fileName As String, ext As String
    Dim x As Variant
    
    dirPath = "C:\Users\X\Documents\"
    ext = ".pdf"
    
    For Each ws In Worksheets
        ws.Select
        nm = ws.Name
        
        fileName = nm
        i = 0
        
        Do
            x = Dir(dirPath & fileName & ext)
            If x = "" Then Exit Do
            i = i + 1
            fileName = nm & "_" & i
        Loop While True
        
        ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
            fileName:=dirPath & fileName & ext, _
            Quality:=xlQualityStandard, IncludeDocProperties:=True, _
            IgnorePrintAreas:=False, OpenAfterPublish:=False
    Next ws

    
End Sub
 
Last edited:
Upvote 0

Forum statistics

Threads
1,215,330
Messages
6,124,305
Members
449,150
Latest member
NyDarR

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