Save each worksheet in workbook as an individual pdf

亡梦爱人 提交于 2020-01-05 05:30:10

问题


I want to loop over all worksheets in a workbook and save them as individual pdfs in the same path as the workbook. The files are named after the worksheet name.

This code below works up until the "wsA.ExportAsFixedFort" line. The error message i get is:

Run-time error '91': Object variable or With block variable not set

But i cant figure out what the issue is...

Any suggestions?

Option Explicit

Sub WorksheetLoop()

Dim wsA As Worksheet
Dim wbA As Workbook
Dim strTime As String
Dim strName As String
Dim strPath As String
Dim strFile As String
Dim strPathFile As String
Dim myFile As Variant
Dim WS_Count As Integer
Dim I As Integer

' Set WS_Count equal to the number of worksheets in the active workbook.
Set wbA = ActiveWorkbook
WS_Count = wbA.Worksheets.Count
strPath = wbA.Path
strTime = Format(Now(), "yyyymmdd\_hhmm")

'get active workbook folder, if saved
strPath = wbA.Path
If strPath = "" Then
  strPath = Application.DefaultFilePath
End If
strPath = strPath & "\"

' Begin the loop.
For I = 1 To WS_Count

    'replace spaces and periods in sheet name
    strName = Replace(wbA.Worksheets(I).Name, " ", "")
    strName = Replace(strName, ".", "_")

    'create default name for savng file
    strFile = strName & "_" & strTime & ".pdf"
    myFile = strPath & strFile

    Debug.Print myFile

    'export to PDF if a folder was selected
    If myFile <> "False" Then
        wsA.ExportAsFixedFormat _
            Type:=xlTypePDF, _
            Filename:=myFile, _
            Quality:=xlQualityStandard, _
            IncludeDocProperties:=True, _
            IgnorePrintAreas:=False, _
            OpenAfterPublish:=False
        'confirmation message with file info
        MsgBox "PDF file has been created: " _
          & vbCrLf _
          & myFile
    End If

Next I

End Sub

回答1:


Try to change like this:

If myFile <> "False" Then
            ActiveSheet.ExportAsFixedFormat _
                    Type:=xlTypePDF, _
                    FileName:=myFile, _
                    Quality:=xlQualityStandard, _
                    IncludeDocProperties:=True, _
                    IgnorePrintAreas:=False, _
                    OpenAfterPublish:=False

Then try to find a way how to loop through the sheets, its a trivial VBA task. In general, in your code wsA was not set. Thus, you got an error.



来源:https://stackoverflow.com/questions/43895717/save-each-worksheet-in-workbook-as-an-individual-pdf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!