使用Excel宏创建pdf

时间:2017-06-09 15:55:09

标签: excel vba excel-vba pdf

我正在尝试在Excel工作簿中为每个工作表创建单独的pdf。这是我正在使用的代码。

Sub CreatePdfs()
' CreatePdfs Macro
' Keyboard Shortcut: Ctrl+o
Dim ws As Worksheet
Dim wsA As Worksheet
Dim wbA As Workbook 
Dim strPath As String
Dim strFile As String
Dim strPathFile As String
Dim myFile As Variant
For Each ws In Worksheets
Set wbA = ActiveWorkbook
Set wsA = ActiveSheet
strPath = wbA.Path
If strPath = "" Then
  strPath = Application.DefaultFilePath
End If
strPath = strPath & "\"
strName = Replace(wsA.Name, " ", "")
strName = Replace(strName, ".", "_")
strFile = strName & ".pdf"
strPathFile = strPath & strFile
ws.Select
nm = wsA.Name

ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=strPathFile, Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False

Next ws 
End Sub  

这“几乎”有效。它为每个工作表创建一个单独的pdf文件(按照它应该)并将其保存在与Excel文件相同的文件夹中(就像它应该的那样),但是将其命名为错误。例如,如果工作簿中有4个工作表,分别为1,2,3和4,则它将工作表2创建为pdf并将其命名为“1”。它将3命名为“2”,将4命名为“3”,将1命名为“4”。

我必须在代码中出现问题。

1 个答案:

答案 0 :(得分:1)

如果您不使用.Select,那么您将不会遇到这个问题。您不需要行Set wbA = ActiveWorkbookSet wsA = ActiveSheet。此外,ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF...变为ws.ExportAsFixedFormat Type:=xlTypePDF...

试试此代码

Sub CreatePdfs()
    ' CreatePdfs Macro
    ' Keyboard Shortcut: Ctrl+o
    Dim ws As Worksheet
    Dim strPath As String, strFile As String, strPathFile As String

    strPath = ThisWorkbook.Path
    If strPath = "" Then strPath = Application.DefaultFilePath
    If Right(strPath, 1) <> "\" Then strPath = strPath & "\"

    For Each ws In ThisWorkbook.Worksheets
        strName = Replace(Replace(ws.Name, " ", ""), ".", "_")
        strFile = strName & ".pdf"
        strPathFile = strPath & strFile

        ws.ExportAsFixedFormat Type:=xlTypePDF, _
        Filename:=strPathFile, Quality:=xlQualityStandard, _
        IncludeDocProperties:=True, IgnorePrintAreas:=False, _
        OpenAfterPublish:=False
    Next ws
End Sub