Excel宏,用于将嵌入式Word文档保存为PDF

时间:2018-09-21 09:19:34

标签: excel vba excel-vba ms-word

我正在使用当前宏将Excel工作簿中的Word文档保存到同一文件夹。保存时有什么方法可以将它们转换为PDF?因此,不是将宏保存到Word,而是将其转换为PDF?我已经成功创建了Word宏以保存为PDF,但是我无法实现它以在Excel中工作。

    Sub MMmachine()
Dim ws As Worksheet: Set ws = Sheets("MAIN")
    'declare and set your worksheet, amend as required
    If ws.Range("B1").Value = True Then
        MYMACRO
    End If
End Sub

Sub MYMACRO()
Const wdFormatDocument = 0
Dim sh As Shape
Dim objWord As Object ''Word.Document
Dim objOLE As OLEObject
Dim wSystem As Worksheet
On Error Resume Next

Set wSystem = Worksheets("MAIN")
''The shape holding the object from 'Create from file'
''Object 2 is the name of the shape
Set sh = wSystem.Shapes("Object 6")
''Activate the contents of the object
sh.OLEFormat.Activate
''The OLE Object contained
Set objOLE = sh.OLEFormat.Object
''This is the bit that took time
Set objWord = objOLE.Object
objWord.Application.Visible = False
''Easy enough
    objWord.SaveAs2 Filename:=ActiveWorkbook.Path & "\MyFile.docx", FileFormat:= _
    wdFormatDocumentDefault
objWord.Application.Quit
sh.OLEFormat.Delete
End Sub

1 个答案:

答案 0 :(得分:1)

所需要做的只是微不足道的代码更改:

objWord.SaveAs2 Filename:=ActiveWorkbook.Path & "\MyFile.pdf", FileFormat:=wdFormatPDF

或:

objWord.SaveAs2 ActiveWorkbook.Path & "\MyFile.pdf", 17