I want to prepare and show the Find/Replace dialog. However, the following code shows the dialog in a modal status, and you can't get to the document text.

Any ideas how make it modeless, just like you get from Ctl-H?

Public Sub AutoFind()
    On Error GoTo myErrorHandler

    Selection.HomeKey Unit:=wdStory

    Dim theDialog As dialog
    Set theDialog = Application.Dialogs(wdDialogEditReplace)
    theDialog.Find = "the"
    theDialog.replace = "an"

End Sub

It looks like modal is the only behavior by design, but there is a work-around:


With the proper ID, this is analogous to hitting the button with your mouse to open the dialog.

I have never used this myself except to confirm it works in v2010, and my instinct says one ought look for a way to confirm or derive the ID number (or perhaps there's a constant one can use) since this is a hard-coded "magic number" that may change from version to version.

In Word 2010, which I have handy, "Find" is ID:=141, "Replace" is ID:=313.

So you can set up a "programmatic" search, and then call use the above CommandBars method to open the dialog. It ought to be populated the way you want it and ought to be non-modal.

Sub TestMacro()
    With Selection.Find
        .Text = "test find field"
        .Replacement.Text = "test replace field"
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With

end sub

Of course, non-modal also means code execution continues immediately.


This was my hacky solution:

SendKeys "^h"   ' Hack to obtain "Dialogs(wdDialogEditReplace).Show" modelessly.
' MS Disclaimer: SendKeys is unreliable as to there being no certainty as to where focus is when called.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.