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?

macropod
07-31-2008, 03:45 AM
Hi MWE,

I don't profess to understand why, but here's a solution:
Replace -
Set wrdRange = ActiveDocument.Range(Start:=Index, End:=Index + 2)
With -
Set wrdRange = ActiveDocument.Characters(Index)
wrdRange.MoveEnd Unit:=wdCharacter, Count:=2

MWE
08-01-2008, 11:46 AM
Hi MWE,

I don't profess to understand why, but here's a solution:
Replace -
Set wrdRange = ActiveDocument.Range(Start:=Index, End:=Index + 2)
With -
Set wrdRange = ActiveDocument.Characters(Index)
wrdRange.MoveEnd Unit:=wdCharacter, Count:=2thanks for the reply and solution. Were you were able to replicate the problem? Is this a known bug or have I stumbled onto something new?

I did some additonal testing and, as one might suspect, the length of the search string is not important; the range text is always all characters except the first.

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