The error "Runtime error 5692" gets thrown by range.Find.Execute
under some circumstances, including sometimes when the range is empty, and sometimes when a regex search is done with a malformed regex.
What does this error mean? Is the error documented anywhere?开发者_C百科 From my position of ignorance, it is unpredictable.
Based on my testing with Word 2007 (under Crossover FWIW), I think this is occurring when the "Find" text (Find.Text) contains invalid characters for the Find.MatchWildcards flag. That flag is sticky, so if the user happened to use it on their last manual find or find/replace the VBA script would be contaminated with that sticky setting, resulting in the runtime error 5692 when you use characters such as '^p' and '^t' in your Find.Text string. Explicitly setting "Find.MatchWildcards = False" before running Find.Execute prevents the error. You'd think we could have had some documentation or a better error message though.
Test case that always fails:
Sub ReplaceInDocument
Dim wdReplaceAll
'set the value for the replace "constant"
wdReplaceAll = 2
With Selection.Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = "^p"
.Replacement.Text = "replacement text "
.Forward = True
.Wrap = 1
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = True
.MatchSoundsLike = False
.MatchAllWordForms = False
'the Replace argument is the 11'th argument
.Execute , , , , , , , , , , wdReplaceAll
End With
End Sub
Test case that works:
Sub ReplaceInDocument
Dim wdReplaceAll
'set the value for the replace "constant"
wdReplaceAll = 2
With Selection.Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = "^p"
.Replacement.Text = "replacement text "
.Forward = True
.Wrap = 1
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
'the Replace argument is the 11'th argument
.Execute , , , , , , , , , , wdReplaceAll
End With
End Sub
I did some research, but—like you—I found no documentation.
It appears that this error can sometimes be caused by not clearing find/replace text.
I have tested the code below with several different inputs, and it is running without errors. Note: code requires checking Tools -> References -> Microsoft Word xx.0 Object Library.
Sub TextReplace()
Dim oWord As Word.Application
Dim oDoc As Word.Document
Dim oFind As Find
Set oWord = CreateObject("Word.Application")
oWord.Visible = True
Set oDoc = oWord.Documents.Add("C:\in.doc")
Set oFind = oDoc.Range.Find
oFind.Execute "foo", , , , , , , , , "bar", wdReplaceAll
oDoc.SaveAs ("C:\out.doc")
oDoc.Close
oWord.Visible = False
End Sub
Feel free to update your question with any errors you get while running this code.
精彩评论