gpt4 book ai didi

vba - 用于突出显示多个单词的 Microsoft Word 宏

转载 作者:行者123 更新时间:2023-12-04 12:35:42 25 4
gpt4 key购买 nike

我的目的是创建一个非常基本的宏来查找一系列单词并突出显示它们。不幸的是,我不知道如何一步完成多个单词。例如,以下代码有效:

Sub Macro1()
'
' Macro1 Macro
'
'
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
Selection.Find.Replacement.Highlight = True
With Selection.Find
.Text = "MJ:"
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindContinue
.Format = True
.MatchCase = True
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute Replace:=wdReplaceAll
End Sub

但是,如果我添加另一个 .Text =行,然后是 MJ:被忽略。有任何想法吗?

最佳答案

如果您只查找几个单词,只需在同一个宏中进行多次查找和替换即可完成您想要的操作。例如,以下将以黄色突出显示所有出现的“target1”和“target2”

Sub HighlightTargets()

' --------CODE TO HIGHLIGHT TARGET 1-------------------
Options.DefaultHighlightColorIndex = wdYellow
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
Selection.Find.Replacement.Highlight = True
With Selection.Find
.Text = "target1"
.Replacement.Text = "target1"
.Forward = True
.Wrap = wdFindContinue
.Format = True
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute Replace:=wdReplaceAll

' --------CODE TO HIGHLIGHT TARGET 1-------------------
Options.DefaultHighlightColorIndex = wdYellow
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
Selection.Find.Replacement.Highlight = True
With Selection.Find
.Text = "target2"
.Replacement.Text = "target2"
.Forward = True
.Wrap = wdFindContinue
.Format = True
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute Replace:=wdReplaceAll
End Sub

或者,以下代码将让您将所有术语添加到一行中突出显示,这可能更容易使用。
Sub HighlightTargets2()

Dim range As range
Dim i As Long
Dim TargetList

TargetList = Array("target1", "target2", "target3") ' put list of terms to find here

For i = 0 To UBound(TargetList)

Set range = ActiveDocument.range

With range.Find
.Text = TargetList(i)
.Format = True
.MatchCase = True
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False

Do While .Execute(Forward:=True) = True
range.HighlightColorIndex = wdYellow

Loop

End With
Next

End Sub

关于vba - 用于突出显示多个单词的 Microsoft Word 宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9399655/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com