vba 仅查找样式“标题 1”的文本(Range.Find 以匹配样式)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9286927/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Find text only of style "Heading 1" (Range.Find to match style)
提问by Matt Rowles
I am trying to find some text in my document that only appears in "Heading 1" styles. So far, no avail.
我试图在我的文档中找到一些只出现在“标题 1”样式中的文本。到目前为止,无济于事。
Sample Code:
示例代码:
With ThisDocument.Range.Find
.Text = "The Heading"
.Style = "Heading 1" 'Does not work
.Execute
If .Found Then Debug.Print "Found"
End With
Just a note, it keeps stopping at the table of contents.
请注意,它一直停在目录处。
Edit: fixed the mispelt 'if' statement
编辑:修复了拼写错误的“if”语句
采纳答案by markblandford
Your code looks good to me. My best guess is that the 'Heading 1' style exists in your table of contents?
你的代码对我来说看起来不错。我最好的猜测是“标题 1”样式存在于您的目录中?
The code below should continue the find, 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
I hope this helps.
我希望这有帮助。
回答by AdmiralThrawn
I found this question on Google and the code in the question did not work for me. I have made the following changes to fix it:
我在谷歌上发现了这个问题,问题中的代码对我不起作用。我进行了以下更改以修复它:
- I changed
Selection.Find.Style = "Heading 1"
to an object. - I changed the code to grab the boolean result of the search from
.Execute
rather than.Found
- 我变成
Selection.Find.Style = "Heading 1"
了一个对象。 - 我更改了代码以从中获取搜索的布尔结果
.Execute
而不是.Found
I hope this helps some other Googlers.
我希望这能帮助其他一些 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
回答by perlhacker9876
The reason I think it is not working is because you have to set the
我认为它不起作用的原因是因为您必须设置
.format = true
flag, and you mayhave to specify the style via the .Styles method:
标志,您可能必须通过 .Styles 方法指定样式:
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