Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find text only of style "Heading 1" (Range.Find to match style)

Tags:

ms-word

vba

I am trying to find some text in my document that only appears in "Heading 1" styles. So far, no avail.

Sample Code:

With ThisDocument.Range.Find
    .Text = "The Heading"
    .Style = "Heading 1" 'Does not work
    .Execute
    If .Found Then Debug.Print "Found"
End With

Just a note, it keeps stopping at the table of contents.

Edit: fixed the mispelt 'if' statement

like image 881
Matt Rowles Avatar asked Feb 15 '12 01:02

Matt Rowles


People also ask

How do you find the Heading 1 style in Word?

To add a heading style Type the text you want into a Word document. Select a sentence that you want to add a header to. Select Home > Styles (or press Alt+H, then L), and then select the heading you want, such as the Heading 1 button.

How do you update the Heading 1 style to match the selection?

○ Highlight the text of your title. Format the text with the font, size, color, etc. ○ Right-click on Heading 1 and select “Update Heading 1 to match selection” ○ The text in the Heading 1 box will update to the format you just created.

What is the difference between Heading 1 and Heading 2 in Word?

Heading 1 – page title or main content. There is usually only 1. Heading 2 – a major section heading. Heading 3 – a subsection heading of a major section.

How do I see all heading styles in Word?

On the Home tab, click the Styles Dialog Box Launcher, and then click Options. Under Select styles to show, click All styles. All styles are displayed in the Styles task pane.


1 Answers

Your code looks good to me. My best guess is that the 'Heading 1' style exists in your table of contents?

The code below should continue the find, finding all occurrences:

Dim blnFound As Boolean

With ThisDocument.Range.Find
    .Text = "The Heading"
    .Style = "Heading 1"

    Do
        blnFound = .Execute
        If blnFound Then
            Debug.Print "Found"
        Else
            Exit Do
        End If
    Loop
End With

I hope this helps.

like image 157
markblandford Avatar answered Oct 17 '22 22:10

markblandford