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

I am trying to find text in my document that appears only in the "Heading 1" styles. Not yet.

Code example:

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

Just notice, it continues to stop in the table of contents.

Edit: fixed mispelt 'if' expression

+4
source share
3 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 search, 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 

Hope this helps.

+3
source

I found this question on Google and the code in the question did not work for me. I fixed the following changes:

  • I changed Selection.Find.Style = "Heading 1" to an object.
  • I changed the code to capture the boolean search result from .Execute , not .Found

I hope this helps some other google.

 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 
+1
source

The reason I think it doesn’t work is because you should install

 .format = true 

and you may need to specify a style using 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 
+1
source

Source: https://habr.com/ru/post/1396543/


All Articles