Matt Rowles
Matt Rowles

Reputation: 8050

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

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

Upvotes: 6

Views: 21961

Answers (3)

perlhacker9876
perlhacker9876

Reputation: 69

The reason I think it is not working is because you have to set the

.format = true

flag, and you may have to specify the style via the .Styles method:

With ThisDocument.Range.Find
    .Text = "The Heading"
    .Format = true   <<< -------- Tells Word to look for a special formatting
    .Style = ThisDocument.Styles("Heading 1")

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

Upvotes: 2

RedDragonWebDesign
RedDragonWebDesign

Reputation: 2571

I found this question on Google and the code in the question did not work for me. I have made the following changes to fix it:

  • I changed Selection.Find.Style = "Heading 1" to an object.
  • I changed the code to grab the boolean result of the search from .Execute rather than .Found

I hope this helps some other Googlers.

With ThisDocument.Range.Find
    .Text = "The Heading"
    .Style = ActiveDocument.Styles("Heading 1")

    Dim SearchSuccessful As Boolean
    SearchSuccessful = .Execute

    If SearchSuccessful Then
        ' code
    Else
        ' code
    End If
End With

Upvotes: 1

markblandford
markblandford

Reputation: 3193

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.

Upvotes: 5

Related Questions