使用Word时,间歇性462错误

我在代码中出现了最令人困惑的一组错误。 目标只是从模板创build一个Word文档,并使用查找/replace来编辑文档以填充Excel中的一些数据。 这是症状:

  • 当我第一次运行代码时,一切正常
  • 下次运行代码时,根据我在调用之前做的事情,发生了两件事情之一:
    • 如果我再次运行代码之前closures了单词文档,第二次运行它(以及之后的每个偶数运行)都会失败。 即使我已经closures了用户表单并从VBA编辑器重新编辑代码,也会发生这种情况。 我认为这与绑定单词对象有关,但我是VBA新手,并没有看到我做错了什么。
    • 如果我没有closuresword文档,只需再次按下button,代码就会运行,并生成一个新的文档,但不能将其设置为活动文档,因为它只是编辑了我生成的第一个文档。

这是违规的代码:

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 

Generate_Click您可以创build一个由variableswordApp引用的Word实例,但该variables不包含在被调用的子FindReplace的范围内。

要解决这个问题你有select:

  1. 创build一个全局variables来引用Word实例(也可以被FindReplace访问)或者

  2. 将其他parameter passing给FindReplace通过它可以使用该Word实例,而不需要Globalvariables。

试试这个:

 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