VBA:在Excel中如何将Word文档另存为PDF? [英] VBA: Within Excel how do I save a word document as a PDF?
问题描述
我有一些代码可以将Excel文件中的数据复制并粘贴到Word文档中,如何获取该Word文档另存为PDF?
I have some code that copies and pastes data from an Excel file into a word document, how can I get that word document to save as a PDF?
我的代码如下:
Sub RetailerGraphs()
Dim Location As String
Dim Detail As String
Worksheets("-Summary").Activate
Range("AE9").Select
While ActiveCell.Value <> ""
ActiveCell.Offset(1, 0).Select
Location = ActiveCell.Value
Worksheets("Detail Summary").Activate
Range("B7").Value = Location
Dim objWord, objDoc As Object
ActiveWindow.View = xlNormalView
Set objWord = CreateObject("Word.Application")
Set objDoc = objWord.Documents.Add
Range("AH40").Select
While ActiveCell <> ""
ActiveCell.Offset(1, 0).Select
Detail = ActiveCell.Value
Range("B11").Value = Detail
Application.Wait (Now + TimeValue("0:00:05"))
Range("A1:Z111").CopyPicture Appearance:=xlScreen, Format:=xlPicture
objWord.Visible = True
objWord.Selection.Paste
objWord.Selection.TypeParagraph
Set objSelection = objWord.Selection
objSelection.InsertBreak (wdPageBreak)
If ActiveCell.Value = "END" Then
objWord.SaveAs2 "C:\Docs\MyDoc.pdf"
End If
Wend
Worksheets("-Summary").Activate
Wend
End Sub
行内:
If ActiveCell.Value = "END" Then
End If
我尝试了以下代码来尝试将其保存为PDF:
I have tried the following code to try to get it to save as a PDF:
objWord.ExportAsFixedFormat OutputFileName:="C:\wordtest.pdf", _
ExportFormat:=wdExportFormatPDF
objWord.ExportAsFixedFormat OutputFileName:="C:\Documents and Settings\All Users\Desktop\YourFile.pdf", ExportFormat:=wdExportFormatPDF
objDoc.ExportAsFixedFormat OutputFileName:="C:\Documents and Settings\All Users\Desktop\YourFile.pdf", ExportFormat:=wdExportFormatPDF
但是我在尝试将其导出为PDF的那一行出现错误,例如objWord.SaveAs2 "C:\Docs\MyDoc.pdf"
:
But I get the error on the line where I try to export it as a PDF, e.g. objWord.SaveAs2 "C:\Docs\MyDoc.pdf"
:
Run-time error '438':
Object doesn't support this property or method
有人可以帮忙吗?
注意:我确保在引用中选中"Microsoft Word 14.0对象库",并且将位置更改为必要的目录,而不是使用上面的目录.
Note: I have ensured that "Microsoft Word 14.0 Object Library" is ticked in the references, and I change the location to the necessary directory rather than using the above.
推荐答案
ExportAsFixedFormat
是Word.Document(objDoc)的方法,而不是Word.Application(objWord)的方法.所以
ExportAsFixedFormat
is a method of Word.Document (objDoc), not Word.Application (objWord). So
objDoc.ExportAsFixedFormat OutputFileName:="C:\Docs\File.pdf", ExportFormat:=wdExportFormatPDF
应该工作.
这是否也会产生错误?哪个?
Does this give an error too? Which?
这篇关于VBA:在Excel中如何将Word文档另存为PDF?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!