Possible bug, when cyling into a selection.

  • Thread starter David Joseph Bonnici
  • Start date
D

David Joseph Bonnici

Hi, i tried to find a way to extract the words that are in bold in a
word document. I have written this code.

intBoldState = 0
For lngRangeTrack = 1 To lngWholeStory Step 500
objWord.Selection.SetRange Start:=lngRangeTrack,
End:=(lngRangeTrack + 499)

For Each objItem In objWords
'Debug.Print " lngRangeTrack = " & lngRangeTrack & " to "
& lngRangeTrack + 9
If ((oldWordStart = objItem.Start)) Then
'Do nothing
Else
oldWordStart = objItem.Start
oldWordEnd = objItem.End

If (intBoldState <> objItem.Bold) Then
intBoldState = objItem.Bold
tso.Write (vbNewLine)
End If
tso.Write (objItem.Text)
'Debug.Print objItem.Text & " Start: " & objItem.Start
& " End: " & objItem.End
End If
Next
Next

What is happening is that, not all the words are appearing in the
objItem. Every now and then it skips a character, and I am quite sure
that it is not due to my fault.

David
 
D

David Joseph Bonnici

Let me reword it. I am cycling trough a words collection and I am not
getting back all the text I am expecting. every now and then it just decides
to leave out a character.
 
J

Jay Freedman

Hi David,

Let me suggest that playing games with the Selection character-by-character,
especially when trying to mix it with the words collection, is completely
the wrong approach. It's prone to logic errors (because the Start and End of
a range include nonprinting characters in their counts, while the Words
collection does not). It's also fatally slow on large documents.

Instead, try the approach of making a copy of the entire document and then
using a ReplaceAll to delete everything that isn't bold:

Dim oSourceDoc As Document
Dim oDestDoc As Document
Dim oRg As Range

Set oSourceDoc = ActiveDocument
Set oDestDoc = Documents.Add
oDestDoc.Range.FormattedText = _
oSourceDoc.Range.FormattedText

Set oRg = oDestDoc.Range
With oRg.Find
.ClearFormatting
.Replacement.ClearFormatting
.Format = True
.Font.Bold = False
.Text = ""
.Replacement.Text = ""
.Execute Replace:=wdReplaceAll
End With

This can be tweaked in various ways, for example by using a wildcard search
to leave certain characters untouched.

Let me also suggest that any further posts on this subject ought to go into
one of the VBA newsgroups.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top