仅查找样式“标题 1”的文本(Range.Find 以匹配样式)

Mat*_*les 5 vba ms-word

我试图在我的文档中找到一些只出现在“标题 1”样式中的文本。到目前为止,无济于事。

示例代码:

With ThisDocument.Range.Find
    .Text = "The Heading"
    .Style = "Heading 1" 'Does not work
    .Execute
    If .Found Then Debug.Print "Found"
End With
Run Code Online (Sandbox Code Playgroud)

请注意,它一直停在目录处。

编辑:修复了拼写错误的“if”语句

mar*_*ord 5

你的代码对我来说看起来不错。我最好的猜测是您的目录中存在“标题 1”样式?

下面的代码应该继续查找,查找所有出现的情况:

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
Run Code Online (Sandbox Code Playgroud)

我希望这有帮助。

  • 将 Debug.Print "Found" 替换为 Debug.Print .Parent.Information(wdFirstCharacterLineNumber) 将返回行号 (2认同)
  • @MattRowles从那时起我似乎找到了内置样式引用问题的解决方案:http://msdn.microsoft.com/en-us/library/microsoft.office.interop.word.wdbuiltinstyle(v=office.11​​) .aspx,但我没有尝试。 (2认同)