Dynamic saving to PDF only certain Sheets in Excel

2019-09-07 19:30发布

I have an Excel workbook with 5 sheets(I'm simplifying for clarity here):

'DataMaster'

'CityData S'

'TownData S'

'TownlandData S'

'StreetData S'

Sometimes there are additional sheets/tabs but the sheets to be saved are all suffixed with the ' S' suffix. 'Datamaster' here does not need to be saved.

I wish to export/save to PDF using a loop that

1) Only will look at sheets with rightmost 2 characters in their names being ' S'.

2) Will not care if there 3 or 10 of these sheets.

3) will export to PDF with filename being the leftphrase in the sheetname.

Thus the export would be:

CityData.PDF , 
TownData.PDF , 
TownlandData.PDF , 
StreetData.PDF

Any tips/help would be appreciated, I have the basic export to PDF code only.

1条回答
一纸荒年 Trace。
2楼-- · 2019-09-07 20:22

You can use a For Each loop to loop through every worksheet in your workbook. You can use an If to test if the Right() two characters match.

Something like:

Sub SaveToPDF
    Dim ws as worksheet

    'Loop through worksheets, each worksheet is assigned to variable "ws" declared above:
    For Each ws in ThisWorkbook.Worksheets
        If Right(ws.name, 2) = " S" Then
            'export as pdf
            ws.ExportAsFixedFormat _
                Type:=xlTypePDF, _
                Filename:="C:\" & Left(ws.name, len(ws.name)-2) & ".pdf", _
                Quality:=xlQualityStandard, _
                IncludeDocProperties:=True, _
                IgnorePrintAreas:=False, _
                OpenAfterPublish:=True
        End If
    Next ws
End Sub
查看更多
登录 后发表回答