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

馋奶兔 提交于 2020-01-03 17:46:22

问题


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


回答1:


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.




回答2:


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



回答3:


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


来源:https://stackoverflow.com/questions/9286927/find-text-only-of-style-heading-1-range-find-to-match-style

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!