簡體   English   中英

使用Word時出現間歇性462錯誤

[英]Intermittent 462 Error when Using Word

我的代碼中出現了最令人困惑的錯誤。 目的只是從模板創建Word文檔,然后使用查找/替換來編輯文檔以填充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

Generate_Click ,創建一個由wordApp變量引用的Word實例,但該變量不包含在被稱為Sub FindReplace的范圍內。

要解決此問題,您可以選擇:

  1. 創建一個全局變量以引用Word實例(FindReplace也可以訪問它)或

  2. 將附加參數傳遞給FindReplace通過它可以使用該Word實例而無需全局變量。

嘗試以下方法:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM