为所选Excel工作表创建PDF文件

3
我正在尝试为一组选定的工作表创建单独的PDF,名称由工作表名称和一个单元格的内容确定。
代码如下:
Sub SaveWorksheetsAsPDFs()
    Dim sFile       As String
    Dim sPath       As String
    Dim sh          As Object
    Dim InvDate     As String

    With ActiveWorkbook

        sPath = .Path & "\"
        For Each sh In ActiveWindow.SelectedSheets

            InvDate = Format(Range("G9"), "dd-mm-yy")
            sFile = sh.Name & " - Invoice - " & InvDate & ".pdf"
            sh.ExportAsFixedFormat Type:=xlTypePDF, _
                                   Filename:=sPath & sFile, _
                                   Quality:=xlQualityStandard, _
                                   IncludeDocProperties:=False, _
                                   IgnorePrintAreas:=False, _
                                   OpenAfterPublish:=False
        Next sh
    End With
End Sub

已经创建了单独的PDF并正确地命名,但是PDF包含了所有选定的工作表而不是其中一个。

1个回答

2

根据我的经验,我发现 ExportAsFixedFormat 总是会导出所有选定的工作表。

你可以通过在 For Each 后添加 sh.Select 来解决这个问题,然后它应该按照你在 OP 中描述的方式工作。

编辑后的代码:

Sub SaveWorksheetsAsPDFs()
    Dim sFile       As String
    Dim sPath       As String
    Dim sh          As Object
    Dim InvDate     As String


    With ActiveWorkbook

        sPath = .Path & "\"
        For Each sh In ActiveWindow.SelectedSheets
            sh.Select '<----- New LINE

            InvDate = Format(Range("G9"), "dd-mm-yy")
                sFile = sh.Name & " - Invoice - " & InvDate & ".pdf"
                sh.ExportAsFixedFormat Type:=xlTypePDF, _
                                        Filename:=sPath & sFile, _
                                        Quality:=xlQualityStandard, _
                                        IncludeDocProperties:=True, _
                                        IgnorePrintAreas:=True, _
                                        OpenAfterPublish:=False
        Next sh
    End With
End Sub

希望这可以帮助你实现你的目标。 :)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接