首页 > 解决方案 > VBA在Excel中为Word文档执行宏

问题描述

我有一个包含 Word 文档信息的 excel 计算。我想要的是打开word文档并将其自动保存为pdf - 在Excel中使用宏。

我已经尝试了以下方法:

Set WordApp = CreateObject("Word.Application")
With WordApp.Application
   .Visible = True
   .Documents.Open (LocationTemplate)
        .ExportAsFixedFormat OutputFileName:= _
        OfferPath, _
        ExportFormat:=wdExportFormatPDF, OpenAfterExport:=True, OptimizeFor:= _
        wdExportOptimizeForPrint, Range:=wdExportAllDocument, From:=1, To:=1, _
        Item:=wdExportDocumentContent, IncludeDocProps:=True, KeepIRM:=True, _
        CreateBookmarks:=wdExportCreateNoBookmarks, DocStructureTags:=True, _
        BitmapMissingFonts:=True, UseISO19005_1:=False
        ChangeFileOpenDirectory _
        DestinationPath
    .Quit

End With

错误是什么?期待您的支持。

标签: excelvbams-word

解决方案


错误是您.ExportAsFixedFormat在 Word.Application 对象上执行。此方法对Word 文档有效。您的代码应该更像下面的代码。

请注意,我已经添加了变量声明WordAppWordDoc代码来释放这些对象。

Dim WordApp as Object
Dim WordDoc as Object
Set WordApp = CreateObject("Word.Application")
With WordApp.Application
   .Visible = True
   Set WordDoc = .Documents.Open (LocationTemplate)
   WordDoc.ExportAsFixedFormat OutputFileName:= _
        OfferPath, _
        ExportFormat:=wdExportFormatPDF, OpenAfterExport:=True, OptimizeFor:= _
        wdExportOptimizeForPrint, Range:=wdExportAllDocument, From:=1, To:=1, _
        Item:=wdExportDocumentContent, IncludeDocProps:=True, KeepIRM:=True, _
        CreateBookmarks:=wdExportCreateNoBookmarks, DocStructureTags:=True, _
        BitmapMissingFonts:=True, UseISO19005_1:=False
    .Quit 0 'To not save changes to the document, just close it
    Set WordDoc = Nothing
End With
Set WordApp = Nothing

推荐阅读