如果文件已存在,则vba无法从excel导出为pdf

时间:2015-08-26 16:19:32

标签: vba excel-vba excel

Sub printPdf()
Dim strPath As String
Dim myFile As Variant
Dim strFile As String
'On Error GoTo errHandler
Set ws = Application.ActiveSheet

'enter name and select folder for file
' start in current workbook folder
strFile = Replace(Replace(ws.Name, " ", "_"), ".", "_") _
            & ".pdf"
strfolder = ThisWorkbook.Path & "\myPdfFiles"

If Len(Dir(strfolder, vbDirectory)) = 0 Then
  MkDir (strfolder)
End If

strFile = strfolder & "\" & strFile

    ws.ExportAsFixedFormat _
        Type:=xlTypePDF, _
        Filename:=strFile, _
        Quality:=xlQualityStandard, _
        IncludeDocProperties:=True, _
        IgnorePrintAreas:=False, _
        OpenAfterPublish:=False
    Call closews


exitHandler:
    Exit Sub
errHandler:
    MsgBox "Could not create PDF file " & Err & ": " & Error(Err)
    Resume exitHandler
End Sub

我在保存pdf文件时遇到问题。 如果该文件已存在于该文件夹中并对其进行了一些更改,则宏将崩溃,调试器指向openAfterPulish行并显示以下运行时错误。

-2214701887(80071779)
 “文件未保存。”

我的目标是excel应该自动覆盖旧文件。当我手动保存文件时,Excel会提示我是否要覆盖文件,但是当我运行上面的代码时会崩溃。

0 个答案:

没有答案