简体   繁体   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

I am having an issue with saving the pdf files. 我在保存pdf文件时遇到问题。 If the file already exists in the folder and has some changes made to it the macro will crash with the debugger pointing at the openAfterPulish line and display the following runtime error. 如果该文件已经存在于文件夹中并且对其进行了一些更改,则该宏将崩溃,并且调试器指向openAfterPulish行,并显示以下运行时错误。

-2214701887(80071779) -2214701887(80071779)
"Document not saved." “文档未保存。”

My goal is that excel should automatically overwrite the old files. 我的目标是excel应该自动覆盖旧文件。 Excel will prompt me if I want to overwrite the file when I am saving it manually but crashes when I run the above code. 当我手动保存文件时,Excel会提示我是否要覆盖文件,但是运行上述代码时,Excel会崩溃。

Check if it exists and delete it. 检查它是否存在并将其删除。 In you VBA IDE go to the tools menu and selecte references. 在您的VBA IDE中,转到工具菜单并选择引用。 Select "Microsoft scripting runtime" 选择“ 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