将工作表保存为PDF Excel VBA时出现运行时错误“-2147417848(800010108)”

yquaqz18  于 2023-01-10  发布在  其他
关注(0)|答案(1)|浏览(270)

我使用下面所附的VBA代码将Excel工作表另存为PDF。但是,当我运行VBA代码时,它总是返回运行时错误“-2147417848(800010108)”
请帮助我,我越来越绝望了。对我正在经历的有什么建议吗?
注意:我试图打印的工作表在单元格A1中只包含单词“test

Sub SimplePrintToPDF()

Dim saveLocation As String
saveLocation = "C:\Users\Santo\Downloads\test123.pdf"

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

End Sub

我100%肯定,我的VBA代码是正确的,因为我已经测试了这个代码在另一个设备上运行完美。我已经看过源代码,有建议,如打开Windows功能,重新启动系统等,但没有工作。

nlejzf6q

nlejzf6q1#

导出到PDF并进行错误处理

  • 你的代码看起来“很好”。所有的“小”问题都会导致不同的错误。也许以下内容会帮助你找出问题所在。如果你知道,请分享。
Sub SimplePrintToPDF()

    ' Define constants.
    Const dSubfolderName As String = "Downloads"
    Const dFileName As String = "Test123.pdf"

    On Error GoTo ClearError
    
    ' Build the folder path.
    Dim pSep As String: pSep = Application.PathSeparator
    Dim dFolderPath As String
    dFolderPath = Environ("USERPROFILE") & pSep & dSubfolderName & pSep
    If Len(Dir(dFolderPath, vbDirectory)) = 0 Then
        MsgBox "The path '" & dFolderPath & "' was not found.", vbCritical
        Exit Sub
    End If
    
    ' Build the file path.
    Dim dFilePath As String: dFilePath = dFolderPath & dFileName
    
    ' Check these results in the Immediate window (Ctrl+G).
    Debug.Print "FilePath: " & dFolderPath
    Debug.Print "FileName: " & dFileName
    Debug.Print "FilePath: " & dFilePath
    
    ' Reference the sheet (charts are allowed).
    If ActiveSheet Is Nothing Then
        MsgBox "No visible workbooks open.", vbCritical
        Exit Sub
    End If
    Dim sh As Object: Set sh = ActiveSheet

    ' Export to PDF.
    sh.ExportAsFixedFormat Type:=xlTypePDF, Filename:=dFilePath, _
        Quality:=xlQualityStandard, IncludeDocProperties:=False, _
        IgnorePrintAreas:=False, OpenAfterPublish:=True
    
    ' Explore subfolder.
    'sh.Parent.FollowHyperlink dFolderPath

ProcExit:
    On Error Resume Next
        ' any final code to run after an error
    On Error GoTo 0
    Exit Sub
ClearError:
    MsgBox "Run-time Error '" & Err.Number & "':" & vbLf & Err.Description
    Resume ProcExit
End Sub

相关问题