2014-09-19 286 views
-1

我正在寫這段代碼時遇到問題。當我運行宏時,它給我一個「運行時錯誤」424':所需對象「VBA運行時錯誤424:Word文檔所需的對象SaveAs

ActiveDocument.SaveAs filename:="C:\test\test.docx", _ 
FileFormat:=wdFormatXMLDocument, AddToRecentFiles:=False 

line。

我想這與單詞文檔和單詞窗口的情況有關,但我不知道如何解決它。

任何幫助將不勝感激! (所提到的行之後,我需要關閉Word文檔以及,也許任何人都可以提供幫助的嗎?)

Dim objword As Object 
Dim objDoc As Object 
Dim fNameAndPath As Variant 
Dim fNameAndPath2 As Variant 

fNameAndPath = "C:\test" 
fNameAndPath2 = "C:\test2" 

i = 2 
While Not IsEmpty(Cells(i, 3)) ' or whevever you want to start 
    If Cells(i, 9) = "End of Probation Per" Then 
     Set objword = CreateObject("Word.Application") 
     objword.Visible = True 
     objword.Documents.Open (fNameAndPath) 
     objword.Activate 
     With objword.ActiveDocument 
      .Bookmarks("EmpName").Range.Text = Cells(i, 2).Value 
      .Bookmarks("EndDate").Range.Text = Cells(i, 11).Value 
       ActiveDocument.SaveAs filename:="C:\test\test.docx", _ 
FileFormat:=wdFormatXMLDocument, AddToRecentFiles:=False  
     End With 
     Else: Cells(i, 9).Font.Italic = True 
    End If 
    i = i + 1 
Wend 

End Sub 

回答

1

您需要完全限定對象:

objWord.ActiveDocument.SaveAs filename:="C:\test\test.docx", _ 
FileFormat:=wdFormatXMLDocument, AddToRecentFiles:=False  

還要注意的是,如果您還沒有設置到Word對象庫的引用,不斷wdFormatXMLDocument沒有價值,所以你應該把它定義:

Const wdFormatXMLDocument As Long = 12 

回覆你最後的評論,你可以包括對網絡單元值文件名稱:

objWord.ActiveDocument.SaveAs filename:="C:\test\" & cells(i, 2).value & ".docx", _ 
FileFormat:=wdFormatXMLDocument, AddToRecentFiles:=False 
+0

在這種情況下,你會如何命名FileFormat?我只想要一個docx文檔。 – Casz146 2014-09-19 14:26:39

+0

或者使用FileFormat:= 12或者,最好在你的代碼的頂部添加一個常量:'Const wdFormatXMLDocument As Long = 12' – Rory 2014-09-19 14:43:44

+0

謝謝!我要問另一個問題。代碼是爲了將Cells(i,2)中的值放入新文件名中,以便我可以爲每行創建一個個人文件名?我應該使用書籤值還是使用Excel中的值? – Casz146 2014-09-19 14:58:01

相關問題