Steve Herald
Steve Herald

Reputation: 33

.Find Loop Word 2013

I have a document that has plain text and I want to do some preformatting before I move it to Access. Currently, I'm in Word trying to separate the formatting into titles and text. The document has hundreds of titles and after each title small explanation text (it's an error book with explanations for one machine).

I am trying to put a unique string at the end of a lane that starts with "start-of-title" unique string.

I want to make a macro that finds that string, then goes to the end of the lane and writes " end-of-title" and do that till there are results found.

What I've done so far, and works once, is the following:

Sub test3()
    Selection.Find.ClearFormatting
    With Selection.Find
        .Text = "startoftitle "
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindAsk
        .Format = False
        .MatchCase = True
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With
    Selection.Find.Execute
    Selection.EndKey Unit:=wdLine
    Selection.TypeText Text:=" endoftitle"
End Sub

I've tried doing loops, but sadly I wasn't able to do the right syntax. The problem is that I can't make it loop till there are no results found...

Upvotes: 0

Views: 247

Answers (2)

Steve Herald
Steve Herald

Reputation: 33

I managed to solve it before checking what you've written. Thank you for your help!

Here is the code for anyone with the same problem:

Sub test3()
'
' test3 Macro
'
'
    Selection.Find.ClearFormatting
    With Selection.Find
        .Text = " startoftitle "
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindStop
        .Format = False
        .MatchCase = True
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With
    Do While Selection.Find.Execute = True
        Selection.EndKey Unit:=wdLine
        Selection.TypeText Text:=" endoftitle"
    Loop
End Sub

Upvotes: 1

ignotus
ignotus

Reputation: 658

This should do it

Sub test3()
    Const STARTTOKEN = "startoftitle "
    Const ENDTOKEN = " endoftitle"

    For i = 1 To ThisDocument.Paragraphs.Count
        If ThisDocument.Paragraphs(i).Range.Style = "Title" _
            And Left(ThisDocument.Paragraphs(i).Range.Text, Len(STARTTOKEN)) <> STARTTOKEN Then

            ThisDocument.Paragraphs(i).Range.Text = STARTTOKEN & ThisDocument.Paragraphs(i).Range.Text & ENDTOKEN

        End If
    Next i
End Sub

Upvotes: 1

Related Questions