MBlackburn
MBlackburn

Reputation: 117

VBA Find & Replace but excluding words before the instance

Lets say I want to use VBA Word to find/replace. I want to find replace the word "page" with "page (title needs bolded" but I ONLY want to do this if the preceding word(s) are not "continued on next"

I tried to find the word and then used key commands to ctrl+shift+left arrow and IF those = "continued on next" do nothing, else replace the "page" with the "page (title needs bolded).

   Sub SpellingSuggestionPage()

Dim wrd As Range
Dim srchText As String, avdText As String, replWord As String
Dim ar() As String
Dim ignoreWord As Boolean

srchText = "page"
avdText = "next"
replWord = "page (title needs bolded)"

ar = Split(avdText, " ")

For Each wrd In ActiveDocument.Words

    ignoreWord = False

    If wrd = srchText Then

        If wrd.Previous(Unit:=wdWord, Count:=1).Text = avdText Or wrd.Previous(Unit:=wdWord, Count:=1).Bold Then
              ignoreWord = True
        End If

        If ignoreWord = False Then
            wrd.Text = replWord
        End If

    End If
Next
End Sub

Upvotes: 0

Views: 2596

Answers (2)

Siddharth Rout
Siddharth Rout

Reputation: 149295

Like this?

Option Explicit

Sub Sample()
    Dim wrd As Range
    Dim srchText As String, avdText As String, replWord As String
    Dim ar() As String
    Dim ignoreWord As Boolean

    srchText = "page"
    avdText = "continued on next"
    replWord = "page (title needs bolded)"

    ar = Split(avdText, " ")

    For Each wrd In ActiveDocument.Words
        ignoreWord = False

        If wrd = srchText Then
            If Trim(wrd.Previous(Unit:=wdWord, Count:=1).Text) = Trim(ar(2)) Then
                If Trim(wrd.Previous(Unit:=wdWord, Count:=2).Text) = Trim(ar(1)) Then
                    If Trim(wrd.Previous(Unit:=wdWord, Count:=3).Text) = Trim(ar(0)) Then
                        ignoreWord = True
                    End If
                End If
            End If

            If ignoreWord = False Then
                wrd.Text = replWord
            End If
        End If
    Next
End Sub

Upvotes: 1

jwatts1980
jwatts1980

Reputation: 7356

If I understand you correctly, I think this might do it:

If InStr(value, "page") > 0 And InStr(value, "continued on next") = 0 Then
    value = Replace(value, "page", "page (title needs bolded)")
End If

That says : if value contains "page" anywhere and it does not contain "continued on next" anywhere, then replace "page" with "page (title needs bolded)".

Upvotes: 1

Related Questions