VBA – 从Excel中保存Word文档作为pdf – 找不到命名的参数

我想让一个Excel脚本创build一个文档文件,并将其保存为PDF文件。 创build文档没有问题,但find正确的代码将其保存为PDF文件似乎是一个问题。 我search了互联网,有许多手册和相同的问题的答案都归结于相同的代码:

ActiveDocument.ExportAsFixedFormat OutputFileName:= _ ActiveDocument.Path & "\" & ActiveDocument.Name & ".pdf", ExportFormat:= _ wdExportFormatPDF, OpenAfterExport:=False, OptimizeFor:= _ wdExportOptimizeForPrint, Range:=wdExportAllDocument, _ Item:=wdExportDocumentContent, IncludeDocProps:=True, KeepIRM:=True, _ CreateBookmarks:=wdExportCreateNoBookmarks, DocStructureTags:=True, _ BitmapMissingFonts:=True, UseISO19005_1:=False 

不知何故,似乎并没有为我做的伎俩,因为它给了我错误“命名的参数未find”。 这是我的脚本(我省略了不相关的行,我确定path和文件名被正确存储)。

 'Dim Word formfield values Dim objWord As Object Dim strDocName As String, strDocName1 As String, strDocName2 As String Dim strMyPath As String 'Declare Word variables Set objWord = CreateObject("word.application") objWord.Visible = True With objWord.activedocument 'fill in a bunch of formfields .ExportAsFixedFormat Type:=xlTypePDF, Filename:=strMyPath & "\" & strDocName2, _ OpenAfterExport:=False .Close End With 

我在这里做错了什么?

它不起作用的原因是Excel不知道任何Word的常量值,如wdExportAllDocumentwdExportCreateNoBookmarks

为了使代码正常工作,您需要点击“工具”—>“参考…”,然后单击“Microsoft Word 14.0对象库”旁边的checkbox,以在项目中添加引用 。 然后,您可以使用您在问题顶部发布的代码清理版本。 请记住,像ActiveDocument这样的全局variables在Excel中不存在,您将不得不使用objWord.ActiveDocument 。 此外,对于你的情况,我会build议切换你的代码使用早期绑定(请参阅这里的差异说明),以便您将具有智能感知。 这可以防止拼写错误导致的麻烦。

感谢Blackhawk!

同时我find了另一个解决scheme。 我需要另一个对象(objWordDoc)variables,我已经用“objWord.activedocument”replace了:

 Set objWordDoc = objWord.Documents.Add(strDocToOpen) With objWordDoc 

不过,你的build议一定会在未来派上用场!