2015-12-02 130 views
0

我正在使用一個vba代碼,它將文件夾中的多個word文檔轉換爲單個pdf文件。多個Word文檔到PDF轉換

問題是我無法將word文件保存爲pdf。

下面是代碼:

 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 

ActiveDocument.ExportAsFixedFormat OutputFileName:=NewFileName, ExportFormat:=wdExportFormatPDF是給錯誤的「因爲沒有文檔是打開此命令不可用」。

我可以打開文檔,但不能將文檔保存爲pdf。 預先感謝您!

回答

1

您正在嘗試使用Excel中的Microsoft Word代碼而無需參考。添加一個引用到的Microsoft Word 15.0對象庫和嘗試這個代碼

'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 
+0

謝謝!有效.. – Striker