Vba – Finding block of text with different formatting in Word document using Macros

ms-wordvba

I'm working on creating a macro in Microsoft Word (2007) for a document that contains text such as this:

(1) Bold heading. Normal text.

With this text I'd like to perform a number of transformations upon the first part – (1) Bold heading. – of that text.

While "(1)" and "Bold heading." have a consistent style (bold and Arial), the space between the two does not (it's Times New Roman, non-bold).

I thought a search for the below would work, without any format restrictions.

"^13(\([0-9]@\)) (?@)."

Unfortunately, there's also cases where text is as follows:

(1) Normal text.

For blocks like this, I want to completely skip the text.

Unfortunately, my wildcard search is going to find these instances too, unless I can restrict it by font styles.

If I could normalize the space in the first case, then I could add the Font restrictions on my wildcard search to grab the correct content.

.Text = "^13(\([0-9]@\)) (?@)."
.Font.Name = "Arial"
.Font.Size = 9
.Font.Bold = True

But, I'd need to be able to grab two differently formatted items in a search to normalize that space, which, from my limited knowledge of VBA, doesn't appear to be possible.

Is there a way to find text with different formatting, in a Word macro?

Thanks!

Best Answer

I wonder if something like this would suit:

Dim s As Range
Dim wd As Range
Dim BoldHead As Boolean
Dim doc As Document

Set doc = Word.Documents("Doc2.doc")

For Each s In doc.Sentences
    If s.Words(1).Bold = True Then
        BoldHead = True
        For Each wd In s.Words
            If Trim(wd) <> vbNullString _
                And wd <> "." _
                And wd.Bold = False Then
                BoldHead = False
            End If
        Next
        If BoldHead Then
            Debug.Print s
        End If
    End If
Next

Note that Word has a nasty enough habit of not counting the numbers, it sees them as automatic.

Related Topic