【问题标题】:Change the color of a specific word in Microsoft Word?更改 Microsoft Word 中特定单词的颜色?
【发布时间】:2021-12-01 11:48:15
【问题描述】:

我看过多篇关于这个主题的文章,但没有一篇对我有帮助,而且大部分都是针对 Excel 的。我想在 word 中使用 vba 代码更改字体颜色。我试过Selection.Font.Color,但也没有用。我知道vba 需要一个具有该特定单词的变量,但我没有这样做。

有人知道怎么做吗?

我使用了一种解决方法来使用此 vba 代码替换单词的字体颜色


With Selection.Find
        .ClearFormatting
        .Text = "hello"
        .Replacement.ClearFormatting
        .Replacement.Text = "hi"
        .Replacement.Font.Color = wdColorBlack 'I added this line
        .Execute Replace:=wdReplaceAll, Forward:=True, _
         Wrap:=wdFindContinue
    End With

但我正在寻找一种更具体的方法来替换 vba 中单词的字体颜色。

【问题讨论】:

  • Selection 取决于您选择的内容....也许您可以包含更多上下文?也许发布您正在使用的代码?
  • 是的,我刚刚注意到使用此代码 ``` With Selection.Find .ClearFormatting Selection.Font.Color = wdColorWhite .Replacement.ClearFormatting .Execute Replace:=wdReplaceAll, Forward:=True End With ` ``如果单词是highlighted,我可以更改颜色,但我不想突出显示单词以更改颜色
  • 然后您需要决定您将使用什么其他方法来告诉 Word 要更改哪个部分。你有没有做更多的研究?有很多不同的选项尝试在答案中向您解释是毫无意义的。
  • 例如这里是一个句子“从黑色到绿色”,然后使用vba应该是这样的:句子=从黑色到绿色“Selection.Font.Color = wdColorWhite
  • @braX 正如我的问题中所解释的,我似乎有多种选择,但它们都是针对 excel 的。如果您知道许多解决方案,您可以成为我的客人并回答这个问题

标签: vba ms-word


【解决方案1】:

如果您想要一段可重用的代码,那么应该接近以下内容:

Sub Tester()
    
    ActiveDocument.Content.Font.Color = vbBlack
    
    ColorText ActiveDocument.Content, "breaks", vbRed
    ColorText ActiveDocument.Content, "it", vbBlue
    ColorText ActiveDocument.Content, "with just", vbGreen

End Sub


Sub ColorText(rng As Range, strFind As String, clr As Long)
    With rng.Find
        .Text = strFind
        .Forward = True
        .Format = False
        .MatchCase = False
        .MatchWholeWord = True
        Do While .Execute()
            rng.Font.Color = clr 'rng is redefined as the found text
        Loop
    End With
End Sub

【讨论】:

  • 当可以使用 FnR 完成时,为什么要使用循环替换颜色?只需回头查看问题中的代码即可找到正确的代码。
  • @TimothyRylatt - 因为我不知道更好?
  • 录制宏会给你语法。您需要设置.Format = True,然后将循环替换为.Replacement.Font.Color = clr,然后是.Execute Replace:=wdReplaceAll, Forward:=True, Wrap:=wdFindStop
猜你喜欢
  • 1970-01-01
  • 2013-11-03
  • 1970-01-01
  • 2016-06-13
  • 2013-01-02
  • 2018-03-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多