Reputation: 12077
I'm trying to list every instance of the "Heading 1" style within my document (to eventually list them in a combobox on a form).
The following code appears to find the instances of "Heading 1", as there are the correct number of entries listed within the Immediate Window, but .text
is returning nothing.
What am I doing wrong? Thanks.
Dim blnFound As Boolean
Dim i as Integer
i = 1
With ThisDocument.Range.Find
.Style = "Heading 1"
Do
blnFound = .Execute
If blnFound Then
Debug.Print i & " " & .Text
i = i + 1
Else
Exit Do
End If
Loop
End With
Upvotes: 0
Views: 2036
Reputation: 123
I don't believe the object you have has a .Text property. Selection has a .Text property. Try this:
Sub FindHeadings()
' October 28, 2014
Dim blnFound As Boolean
Dim i As Integer
i = 1
' Set up the find conditions
Selection.HomeKey Unit:=wdStory
Selection.Find.ClearFormatting
Selection.Find.Style = ActiveDocument.Styles("Heading 1")
With Selection.Find
.Text = ""
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindContinue
.Format = True
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute
Selection.MoveLeft Unit:=wdCharacter, count:=1
'Repeat while you find the style
blnFound = True
While blnFound
With Selection.Find
.Execute
If .Found = True Then
Debug.Print i & " " & Selection.Text
i = i + 1
' Move to the next character
Selection.MoveRight Unit:=wdCharacter, count:=1
Else
Debug.Print "Done"
blnFound = False
End If
End With
Wend
End Sub
Upvotes: 2