[英]Export docx to pdf with vba
我想将 docx 文件从 excel vba 导出为 pdf 文件。 文档 file.docx 已正确打开。 但是,调用方法
ExportAsFixedFormat<\/code>时出错:运行时错误 '5': Invalid procedure call or argument<\/strong> 。
我认为争论是可以的。
下一个小错误:
ActiveDocument.Path<\/code>不起作用。
有一个错误“运行时错误'424':需要对象”因此我使用
WordApp.Documents(myFileName).ExportAsFixedFormat<\/code>而不是
ActiveDocument.ExportAsFixedFormat<\/code> 。
此代码从文件 Macro.xlsm 执行。 我使用 Microsoft Office 2021。
Dim fileNameDoc As String
Dim fileNamePdf As String
Dim WordApp
Set WordApp = CreateObject("Word.Application")
FileNameDoc = "D:\rd\file.docx"
WordApp.Documents.Open FileNameDoc
WordApp.Visible = True
WordApp.Documents(FileNameDoc).Activate ' <- activation doesn't work
fileNamePdf = "D:\rd\file.pdf"
'fileNamePdf = ActiveDocument.Path & "\" & "file.pdf"
' https://docs.microsoft.com/en-us/office/vba/api/word.document.exportasfixedformat
' here is error: Run-time error '5': Invalid procedure call or argument
WordApp.Documents(myFileName).ExportAsFixedFormat OutputFileName:=fileNamePdf, _
ExportFormat:=wdExportFormatPDF, _
OpenAfterExport:=False, _
OptimizeFor:=wdExportOptimizeForPrint, _
Range:=wdExportAllDocument, _
Item:=wdExportDocumentWithMarkup, _
IncludeDocProps:=False, _
CreateBookmarks:=wdExportCreateNoBookmarks, _
BitmapMissingFonts:=True
' https://docs.microsoft.com/en-us/office/vba/api/word.document.close(method)'
WordApp.Documents(myFileName).Close _
'ActiveDocument.Close _
SaveChanges:=wdSaveChanges, _
OriginalFormat:=wdOriginalDocumentFormat
您使用的代码是用于 Word 并使用大量 Word 常量,例如
wdExportFormatPDF<\/code> 、
wdExportOptimizeForPrint<\/code> 、
wdExportDocumentWithMarkup<\/code> 、
wdExportCreateNoBookmarks<\/code> 、
wdSaveChanges<\/code> 、
wdOriginalDocumentFormat<\/code> 。
Excel 不明白这些是什么。
你有两个选择。 最好的选择是设置对 Word 库的引用。 在 Visual Basic 编辑器中,从工具菜单中选择引用。 在生成的对话框页面中向下(大约 16 次),直到您看到 Microsoft Word 对象库的条目并选中它旁边的框。
您的另一个选择是在代码中为要使用的每个 Word 常量创建常量。 您需要使用 Word 中的对象浏览器或联机帮助来查找值。
同样,Excel 也不理解
ActiveDocument<\/code> 。
您需要为希望与
WordApp<\/code>一起使用的任何 Word 对象添加前缀。
但是,如果您使用变量指向您打开的文档会更好:
Set WordDoc = WordApp.Documents.Open(FileNameDoc)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.