【问题标题】:Save each worksheet in workbook as an individual pdf将工作簿中的每个工作表保存为单独的 pdf
【发布时间】:2017-05-10 14:41:09
【问题描述】:

我想遍历工作簿中的所有工作表,并将它们保存为与工作簿相同的路径中的单个 pdf。这些文件以工作表名称命名。

下面的代码一直运行到“wsA.ExportAsFixedFort”行。我得到的错误信息是:

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

但我无法弄清楚问题是什么......

有什么建议吗?

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

【问题讨论】:

    标签: vba excel pdf worksheet


    【解决方案1】:

    尝试这样改变:

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

    然后尝试找到一种方法来遍历工作表,这是一项微不足道的 VBA 任务。 一般来说,在您的代码中 wsA 没有设置。因此,您遇到了错误。

    【讨论】:

    • 非常好,感谢您的时间和指导。现在可以了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多