简体   繁体   English

将 Excel 中的一系列单元格导出到 Word 并将 Word 文档保存为 Word 文件和 PDF 文件

[英]Exporting a range of cells in Excel to Word and saving the Word document as both a Word-file AND a PDF-file

What I am trying to do: Export a range of cells from an Excel worksheet as an image in an existing Word document, and then saving this Word document as both a Word document and a PDF file.我想要做的是:将 Excel 工作表中的一系列单元格导出为现有 Word 文档中的图像,然后将此 Word 文档另存为 Word 文档和 PDF 文件。 The name both the Word file and the PDF file should get, is in a cell in the Excel worksheet. Word 文件和 PDF 文件应获得的名称位于 Excel 工作表的单元格中。

The problem: Almost everything works, except for the .pdf-file.问题:除了 .pdf 文件外,几乎一切正常。 It is generated, but when trying to open it I get an error, saying the file is unreadable.它已生成,但在尝试打开它时出现错误,说该文件不可读。

Can someone help with this?有人可以帮忙吗? The code I use is below - I assembled it from different examples on this and other forums (I really am a VBA beginner)...我使用的代码如下 - 我从这个论坛和其他论坛上的不同例子中组合起来(我真的是一个 VBA 初学者)......

Thank you so much!非常感谢!

The Code:编码:

Sub SaveAsWord()

Dim WordApp As Object
Set WordApp = CreateObject("Word.Application")

Dim WordDoc As Object
Set WordDoc = WordApp.Documents.Open("C:\Users\Jurgen\Documents\remake.docx")

Range("C4:E19").Select
Selection.CopyPicture Appearance:=xlScreen, Format:=xlPicture
WordApp.Visible = True
WordApp.ActiveDocument.Bookmarks("here").Select
Set objSelection = WordApp.Selection
objSelection.Paste

Dim myfilename As String
myfilename = Sheets("Blad1").Range("G15")
WordApp.ActiveDocument.SaveAs2 Filename:="C:\Users\Jurgen\Documents\" & myfilename & ".pdf", _
FileFormat:=wdFormatPDF
WordApp.ActiveDocument.SaveAs2 Filename:="C:\Users\Jurgen\Documents\" & myfilename & ".docx", _
FileFormat:=wdFormatXMLDocument

End Sub

As you do not use Early Binding and it also seems that you do not use Option Explicit the root cause will be that wdFormatPDF is 0 and it should be 17 .由于您不使用 Early Binding 并且您似乎也不使用Option Explicit ,根本原因是wdFormatPDF0 ,它应该是17

Either you use Option Explicit and Early Binding or you just replace the constants with the values like that要么使用Option ExplicitEarly Binding要么只用这样的值替换常量

WordApp.ActiveDocument.SaveAs2 Filename:="C:\\Users\\Jurgen\\Documents\\" & myfilename & ".pdf", _ FileFormat:=17

and

WordApp.ActiveDocument.SaveAs2 Filename:="C:\\Users\\Jurgen\\Documents\\" & myfilename & ".docx", _ FileFormat:=12

Reading material阅读材料

Option Explict 选项显式

Early vs Late Binding早期与晚期绑定

Late Binding后期绑定

Microsoft on Using early binding and late binding in Automation Microsoft 关于在自动化中使用早期绑定和后期绑定

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

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