繁体   English   中英

如果文件已经存在,VBA无法从excel导出到pdf

[英]vba failing to export from excel to pdf if the file already exists

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会提示我是否要覆盖文件,但是运行上述代码时,Excel会崩溃。

检查它是否存在并将其删除。 在您的VBA IDE中,转到工具菜单并选择引用。 选择“ Microsoft脚本运行时”

Dim Response As Integer
Dim fs As FileSystemObject

'We can come back to here after an error.
TryAgain:

 If fs.FileExists(strFile) = True Then
      On Error Goto DeleteError
      fs.DeleteFile(strFile, True)     
 End If

 DeleteError:
 Response = MsgBox("Error deleting file. Do you have it open? Try again?", vbYesNo)
 ' If statement to check if the yes button was selected.
 If Response = vbYes Then
     Goto TryAgain
 Else
     Exit sub
 End If
 On Error Goto 0

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM