locked
Do until...Loop statement using predefined bookmark as condition RRS feed

  • Question

  • I want the following Word 2010 macro (which works) to loop until it reaches the end of the document (Word bookmark \EndOfDoc).

    Can someone please help me by adding the necessary lines for "Do" and "Loop". I have read all the 'Help' files, tried numerous ways, and can't seem to get it right.

    Many thanks

    ' Test Macro
    '
    '

        Sub Test()
        Selection.Find.ClearFormatting
        With Selection.Find
            .Text = "Times Colonist"
            .Replacement.Text = ""
            .Forward = True
            .Wrap = wdFindContinue
            .Format = False
            .MatchCase = False
            .MatchWholeWord = False
            .MatchKashida = False
            .MatchDiacritics = False
            .MatchAlefHamza = False
            .MatchControl = False
            .MatchByte = False
            .CorrectHangulEndings = False
            .HanjaPhoneticHangul = False
            .MatchWildcards = False
            .MatchSoundsLike = False
            .MatchAllWordForms = False
        End With
        Selection.Find.Execute
        Selection.HomeKey Unit:=wdLine
        Selection.TypeText Text:="<pub>"
        Selection.EndKey Unit:=wdLine
        Selection.TypeText Text:="</pub>"
        End Sub
     

    Sunday, August 28, 2011 10:43 PM

Answers

  • Use the following code:

    Selection.HomeKey wdStory
    With Selection.Find
        Do While .Execute(FindText:="Times Colonist", Forward:=True, _
            MatchWildcards:=False, Wrap:=wdFindStop, MatchCase:=True) = True
            With Selection.Bookmarks("\line").Range
                .InsertBefore "<pub>"
                .InsertAfter "</pub>"
            End With
        Loop
    End With

    Be aware that inserting the tags may alter the way in which the document is laid out.


    Doug Robbins - Word MVP dkr[atsymbol]mvps[dot]org
    • Marked as answer by egran2ca Monday, August 29, 2011 5:19 AM
    Monday, August 29, 2011 3:55 AM

All replies

  • Use the following code:

    Selection.HomeKey wdStory
    With Selection.Find
        Do While .Execute(FindText:="Times Colonist", Forward:=True, _
            MatchWildcards:=False, Wrap:=wdFindStop, MatchCase:=True) = True
            With Selection.Bookmarks("\line").Range
                .InsertBefore "<pub>"
                .InsertAfter "</pub>"
            End With
        Loop
    End With

    Be aware that inserting the tags may alter the way in which the document is laid out.


    Doug Robbins - Word MVP dkr[atsymbol]mvps[dot]org
    • Marked as answer by egran2ca Monday, August 29, 2011 5:19 AM
    Monday, August 29, 2011 3:55 AM
  • Thank you so much!! This works perfectly and I can use it as a template to insert other tags.
    Monday, August 29, 2011 5:19 AM