Vba 列出所有的实例;标题1“;风格

Vba 列出所有的实例;标题1“;风格,vba,ms-word,word-style,Vba,Ms Word,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 blnFo

我试图列出文档中“标题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

我不相信您拥有的对象具有.Text属性。所选内容具有.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

谢谢,这很有效。不幸的是,现在我有了一个新问题——我的文档中有一个目录,您的解决方案在该目录和文档中选择了标题。你知道防止这种情况发生的方法吗?谢谢。我想知道你们目录的标题是否也使用标题1样式?如果是这样的话,我建议为该标题使用(或创建)不同的样式,这样它就不会被宏拾取。(注意,我刚才在代码中又添加了一行。)