0

I have this code and it's getting stuck in a loop. I have similar codes and it loops through the doc changing each word only once. When I run this sub it sticks on the first instance and replaces the text over and over.

I want it to find the word "therefore" and if the previous "word" = ; to skip, otherwise change to "therefore (needs joined with ;)".

What am I missing/doing wrong?

Thanks in advance!

 Sub test()

 Dim wrd As Range
 For Each wrd In ActiveDocument.Words
    If InStr(1, wrd, "therefore") <> 0 Then
        If InStr(1, wrd.Previous(Unit:=wdWord, Count:=1).Text, ";") <> 0 Then
        Else
            wrd.Text = "therefore (needs joined with ;)"
        End If
    End If
Next
End Sub
3
  • Have you stepped through your code in debug mode to see what's going on? Commented Jul 9, 2012 at 15:58
  • 1
    Doesn't calling wrd.Previous move the selection pointer back to the previous word? Looks like you are getting to a word, then moving the selection back a word and checking it again. Try calling wrd.Next() after your wrd.Previous() Commented Jul 9, 2012 at 16:00
  • You would be better off using the .Find method of the Document, a defined range or the selection, if you are trying to replace text. I believe what is happening is that you put in new words that haven't been through the "For Each" loop, and that it is finding "therefore" in that set of new words, and replacing it, then doing it again with the new "therefore" word you just put it. Why not just record a Find and Replace macro in Word? Commented Jul 9, 2012 at 18:41

1 Answer 1

2

e.g. try this - as I suspect you are jumping back to the previous word and you are checking it over and over again, the Word DOM is quite a strange one...!

Sub test() 

 Dim wrd As Range 
 For Each wrd In ActiveDocument.Words 
    If InStr(1, wrd, "therefore") <> 0 Then 
        If InStr(1, wrd.Previous(Unit:=wdWord, Count:=1).Text, ";") = 0 Then 
            wrd.Text = "therefore (needs joined with ;)" 
        End If 

        wrd.Next Unit:=wdWord, Count:=1
    End If 
Next 
End Sub 
Sign up to request clarification or add additional context in comments.

4 Comments

It's saying wrd.Next(Unit:=wdWord, Count:=1) is invalid syntax? Did you get that same error?
Try without the parenthesis, vb only requires parenthesis when the methods return value is used
@Charleh Or when Call is explicitly used, but why would you do that? ;-)
Too much coffee maybe? VB makes me shudder.... the boss still uses it though.. when writing NEW apps! Argh!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.