VBA运行时错误424:Word文档SaveAs所需的对象

时间:2014-09-19 14:17:17

标签: excel vba excel-vba word-vba

我在编写这段代码时遇到了问题。当我运行宏时,它会给我一个"运行时错误'''对象需要"在

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

线。

我认为这与“文档”和“窗口”一词有关,但我不知道如何解决它。

任何帮助将不胜感激! (在提到的行之后我也需要关闭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 个答案:

答案 0 :(得分: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