views:

48

answers:

1

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.

Is the error documented anywhere? From my position of ignorance, it is unpredictable.

+1  A: 

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.

Adam Bernier
Great link - yes, that might be what's behind all of the cases I've seen. I'll check this out.
Charles Stewart
Accepted, solves my problem, although I'm still not quite sure what's going on: it seems like this error should be called "Find freaked out about its internal state", and something like adapting Helmut Weber's Resetsearch subroutine (e.g., at http://www.ms-news.net/f4081/wddialogeditfind-issue-133861.html) is the way to ensure the state is not too weird for VBA. I still don't have enough of a picture of what confuses VBA's Find to be able to predict when it will fall over; maybe that's worth putting up a bounty for.
Charles Stewart