【发布时间】:2015-08-24 16:45:53
【问题描述】:
我有一些代码可以将 Excel 文件中的数据复制并粘贴到 word 文档中,我怎样才能将该 word 文档保存为 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:
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":
Run-time error '438':
Object doesn't support this property or method
有人可以帮忙吗?
注意:我已经确保在引用中勾选了“Microsoft Word 14.0 Object Library”,并且我将位置更改为必要的目录而不是使用上面的。
【问题讨论】:
-
不是 VBA,也可能不是您想听到的答案,但我会看看 ITextSharp 和 Codaxy-WKHTMLToPDF。事实证明(根据我的经验),呈现 html 并将其转换为 PDF 比任何其他路线都更容易。如果您可以编写 VBA 来执行使用上述库之一运行 CSharp 应用程序的命令行,那么您可能会有更好的运气。
-
感谢您的建议,但我宁愿坚持使用 VBA 和 Word
-
哪一行导致错误?
-
对不起,我应该补充一下,请看编辑
-
尝试使用以下 .SaveAs2 FileName:="...", _ FileFormat:=..., objWord.SaveAs