使用Word时间歇性462错误

时间:2015-07-27 19:35:32

标签: excel vba excel-vba

我的代码中出现了最令人困惑的错误集。目标只是从模板创建Word文档,并使用find / replace编辑文档以从excel填充一些数据。以下是症状:

  • 当我第一次运行代码时,一切都运行良好
  • 下次运行代码时,根据我在调用之前所做的操作,会发生以下两种情况之一:
    • 如果我在再次运行代码之前关闭了word文档,那么第二次运行它(以及之后的每个偶数运行)它都会失败。即使我已关闭用户窗体并从VBA编辑器重新获取代码,也会发生这种情况。我认为这与绑定单词对象有关,但我是VBA的新手,并没有看到我做错了什么。
    • 如果我没有关闭word文档并再次按下该按钮,则代码会运行并生成一个新文档,但不能将其设置为活动文档,因为它只是编辑了我再次生成的第一个文档。

这是有问题的代码:

Private Sub Generate_Click()
Set wordApp = New Word.Application
wordApp.Visible = True
wordApp.Documents.Add Template:=ThisWorkbook.Path & "\Template.dotx"

FindReplace "[[[DATE_TAG]]]", DateBox.Value
FindReplace "[[[SHIPPING_TAG]]]", POBox.Value
' ... and more of that ...

Set wordApp = Nothing
End Sub

Sub FindReplace(find As String, replace As String)
With Word.ActiveDocument.Range.find ' <---- This line is where the debugger points
                                    '       on the 462 error
    .Text = find
    .Replacement.Text = replace
    .Wrap = wdFindContinue
    .MatchCase = True
    .MatchWholeWord = True
    .Forward = True
    .Execute replace:=wdReplaceAll

    End With
End Sub

1 个答案:

答案 0 :(得分:2)

Generate_Click中,您创建了变量wordApp引用的Word实例,但该变量并未包含在被调用的子FindReplace的范围内。

要解决此问题,您可以选择:

  1. 创建一个全局变量来引用Word实例(FindReplace也可以访问)或

  2. 将其他参数传递给FindReplace,通过该参数可以使用该Word实例而无需全局变量。

  3. 请改为尝试:

    Private Sub Generate_Click()
        Dim wdDoc as Word.Document, wordApp As Word.Application
        Set wordApp = New Word.Application
        wordApp.Visible = True
        Set wdDoc = wordApp.Documents.Add(Template:=ThisWorkbook.Path & "\Template.dotx")
    
        FindReplace wdDoc, "[[[DATE_TAG]]]", DateBox.Value
        FindReplace wdDoc, "[[[SHIPPING_TAG]]]", POBox.Value
        ' ... and more of that ...
    
    Set wordApp = Nothing
    End Sub
    
    Sub FindReplace(wdDoc as Word.Document, find As String, replace As String)
        With wdDoc.Range.find 
        .Text = find
        .Replacement.Text = replace
        .Wrap = wdFindContinue
        .MatchCase = True
        .MatchWholeWord = True
        .Forward = True
        .Execute replace:=wdReplaceAll
    
        End With
    End Sub
    
相关问题