【发布时间】:2020-11-22 09:24:56
【问题描述】:
我有一个需求文档 RD,其中包含 Word 2016 中的“必须”和“应”,我试图找出所有出现的地方并将单词加粗。我正在使用 Microsoft 在其网站上为对象模型提供的示例,用于在此 Web 链接 https://docs.microsoft.com/en-us/office/vba/word/concepts/customizing-word/finding-and-replacing-text-or-formatting
上“如何查找和替换文本”我已将单词“blue”更改为“must”,并添加了第二次搜索“shall”,并在相同的情况下对每个执行了执行。它只找到第一个,即使我设置了 wdFindContinue 也会停止。在下面的代码中,我注释掉了第二次搜索,因为我试图找出为什么它不会在文档中找到所有这些。
这是我用来运行 VBA 代码的 word 中的测试语句。
RD 应遵循模板标准。
RD 应使用 must 这个词。
必须检查 RD 以符合模板标准。 RD 将由组经理签字。
这是我使用的基于 Microsoft 示例的 VBA 代码。最后注释的代码也来自微软,将来可能会使用,因此可以忽略。
Public Sub BoldMustShall()
' This searches the RD document for must and shall
' and changes them to bold.
With ActiveDocument.Content.Find
'.ClearFormatting
.Forward = True
.MatchWholeWord = True
.Wrap = wdFindContinue
'.Text = "must"
.Execute FindText:="must"
If .Found = True Then
.Parent.Bold = True
Debug.Print "Found must "
End If
' .Text = "shall"
'.Execute FindText:="shall"
'If .Found = True Then
'.Parent.Bold = True
'Debug.Print "Found shall "
'End If
End With
' The code having problems is above here.
' Alternate method of doing the same thing for must/shall
' Set myRange = ActiveDocument.Content
' myRange.Find.Execute FindText:="must", Forward:=True
' If myRange.Find.Found = True Then myRange.Bold = True
' A method that will replace all the "shalls" with "must" and then apply above to bold it.
'With Selection.Find
'.ClearFormatting
'.Text = "shall"
'.Replacement.ClearFormatting
'.Replacement.Text = "must"
'.Execute Replace:=wdReplaceAll, Forward:=True, _
'Wrap:=wdFindContinue
' End With
' A method to find all bolded text and unbold it.
'With ActiveDocument.Content.Find
'.ClearFormatting
'.Font.Bold = True
'With .Replacement
'.ClearFormatting
'.Font.Bold = False
'End With
'.Execute FindText:="", ReplaceWith:="", _
'Format:=True, Replace:=wdReplaceAll
'End With
End Sub
【问题讨论】: