列出“标题1”样式的所有实例

时间:2014-10-28 11:19:21

标签: vba ms-word word-vba word-style

我正在尝试在文档中列出“标题1”样式的每个实例(最终将它们列在表单上的组合框中)。

以下代码似乎可以找到“标题1”的实例,因为立即窗口中列出了正确的条目数,但.text没有返回任何内容。

我做错了什么?感谢。

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

1 个答案:

答案 0 :(得分:2)

我不相信你拥有的对象有.Text属性。 Selection具有.Text属性。试试这个:

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