Multiple Word Doc to pdf convert

2019-09-18 16:08发布

I was working with a vba code that will convert multiple word docs in a folder to individual pdf files.

The problem is that I am not able to save the word file as pdf.

Below is the code:

        Sub convertword()


        Dim Filename As String
        Dim irow As Integer
        Dim jsObj As Object
        Dim NewFileName As String
        Dim objWord As Object
        Dim strDocName As String, strDocName1 As String, strDocName2 As String
        Dim strMyPath As String


        irow = 4
        Do While Cells(irow, 2) <> Empty
        Filename = Cells(irow, 2).Value
        NewFileName = Cells(irow, 3).Value

        Set objWord = CreateObject("word.Application")
        objWord.Visible = True

        objWord.Documents.Open Filename

        'Document.SaveAs Filename, wdFormatPDF

        'ActiveDocument.Visible = True

        ActiveDocument.ExportAsFixedFormat OutputFileName:=NewFileName, ExportFormat:=wdExportFormatPDF

        'ActiveDocument.Close

        irow = irow + 1
        Loop
        End Sub

The line ActiveDocument.ExportAsFixedFormat OutputFileName:=NewFileName, ExportFormat:=wdExportFormatPDF is giving error as "This command is not available because no document is open".

I am able to open the doc but just not able to save the doc as pdf. Thank you in advance!

1条回答
看我几分像从前
2楼-- · 2019-09-18 17:05

You are trying to use Microsoft Word code from Excel without a reference. Add a reference to Microsoft Word 15.0 Object Library and try this code

'Set a Reference to Microsoft Word 15.0 Object Library
Sub convertword()
    Dim irow As Integer
    Dim objWord As Word.Application
    Dim newdoc As Word.Document
    Set objWord = New Word.Application
    objWord.Visible = True

    irow = 4
    Do While Cells(irow, 2) <> Empty
        Set newdoc = objWord.Documents.Open(Cells(irow, 2).Value)
        newdoc.ExportAsFixedFormat OutputFileName:=Cells(irow, 3).Value, _
            ExportFormat:=wdExportFormatPDF
        newdoc.Close (False)
        irow = irow + 1
    Loop
    objWord.Quit
End Sub
查看更多
登录 后发表回答