PDA

View Full Version : Strange Behavior in Word 2003 setting a range



MWE
07-30-2008, 02:43 PM
I have noticed some strange behavior in Word 2003. Assume a document with only a single line of text as follows:

12345abc6789

The procedure below looks for all instances of "abc" in the document, displays the index where the text was found, creates a range of that text and displays the text in that range
Sub FindText()

Dim I As Long
Dim Index As Long
Dim NumFound As Long
Dim wrdRange As Range

I = 1
FindText:
Index = InStr(I, ActiveDocument.Range, "abc")
If Index > 0 Then
MsgBox Index
Set wrdRange = ActiveDocument.Range(Start:=Index, End:=Index + 2)
MsgBox wrdRange.Text
I = Index + 3
NumFound = NumFound + 1
GoTo FindText
End If
MsgBox "# found = " & NumFound

set wrdRange = Nothing

End SubThe code is far from pretty, but I am just trying to find out what is wrong with the way I am setting the range.

The range created is not the complete text. It is only the last 2 characters; in this case "bc". Can anyone tell me what I am doing wrong?

mdmackillop
08-03-2008, 03:17 AM
Here's an extract from some code I'm working on.
Running this on your code shows the range start to be 5, not 6
Is it simply a zero based indexing issue?


Option Explicit
Sub CountWords()
Dim txt As String
Dim Strt As Long
Dim i As Long
Dim oRng As Range
Dim col As Long


'Set parameters
txt = "abc" 'InputBox("String to find")
Strt = Len(txt)
col = InputBox("Colour")
'Search Word Document
Set oRng = ActiveDocument.Range
oRng.Collapse wdCollapseStart
'Return data to array
With oRng
With .Find
.ClearFormatting
.Forward = True
.Text = txt
.Execute
While .Found
i = i + 1
oRng.SetRange Start:=oRng.Start, End:=oRng.Start + Strt
'Debug test ***************************
MsgBox "Range start = " & oRng.Start
oRng.HighlightColorIndex = col
'**************************************
oRng.Start = oRng.End
.Execute
Wend
End With
End With
End Sub