【问题标题】:Change Text Colour in Cell Based on Text in Same Cell - Word VBA根据同一单元格中的文本更改单元格中的文本颜色 - Word VBA
【发布时间】:2017-11-14 20:13:39
【问题描述】:

我是 VBA 的新手,所以我正在为看似非常简单的任务而苦苦挣扎。

我在 word 文档的每个单元格中都有几行文本。每个单元格都包含一个类别,例如“科学”或“健康”或其他几个类别中的一个。目前,我实际上只是使用“*”或“@”等特殊字符进行测试。

我需要根据单元格中的类别来更改单元格中所有文本的文本颜色。所以 txt 将是例如绿色代表“科学”,红色代表“健康”。

似乎运行宏是进行这些更改的最快方法(我的最终文档中将有 200 多个这样的单元格,手动着色非常浪费时间)。基本上,我正在努力首先更改单元格中所有文本的颜色,其次如果不满足第一个条件,如何再次进行宏搜索。我想要一个可以为整个文档完成着色的宏,而不是为我需要的每种颜色设置多个宏。

如果您能给我一些我可以使用的 VBA 示例,那将是最有帮助的。我真的很挣扎,你能提供的任何帮助都会为我和我的团队节省很多时间。

【问题讨论】:

  • 您尝试录制宏吗?它会给你代码。
  • 我可以录制一个可以搜索特定文本然后更改该文本颜色的宏,但我需要更改该单元格中所有文本的颜色,而不仅仅是指定的文本。这是我正在努力解决的部分。

标签: vba ms-word


【解决方案1】:

除非您的文档很大或您的关键字列表很大或两者兼而有之,否则这应该会表现得相当好。

Sub ColorCells()

    Dim tbl As Table
    Dim rw As Row
    Dim cll As Cell
    Dim i As Long
    Dim Keywords As Variant, Colors As Variant

    'if you have more than one table, you have to look through them
    Set tbl = ThisDocument.Tables(1)

    'Make two arrays - one with keywords and the second with colors
    'where the colors are in the same position in their array as the
    'keywords are in theirs
    Keywords = Array("Science", "Health")
    Colors = Array(wdBlue, wdDarkRed)

    'Loop through every row in the table
    For Each rw In tbl.Rows
        'Loop through every cell in the row
        For Each cll In rw.Cells
            'Loop through every keyword in your array
            For i = LBound(Keywords) To UBound(Keywords)
                'if the keyword exist, change the color and stop checking
                'further keywords
                If InStr(1, cll.Range.Text, Keywords(i)) > 0 Then
                    cll.Range.Font.ColorIndex = Colors(i)
                    Exit For
                End If
            Next i
        Next cll
    Next rw

End Sub

如果您想使用自定义颜色而不是内置颜色,请将 Colors 数组赋值行更改为

Colors = Array(RGB(192, 192, 192), RGB(188, 25, 67))

以及设置颜色的行

cll.Range.Font.TextColor.RGB = Colors(i)

【讨论】:

  • 非常感谢您看这个!当我运行宏时,我收到以下行的运行时错误: Set tbl = ThisDocument.Tables(1) 您能否再解释一下该部分?如果有帮助,我的文档中确实有多个表格。
  • @PMC11 将ThisDocument 更改为ActiveDocument。使用ThisDocument 将返回运行时错误 5941
  • @dwirony 非常好,非常感谢现在正在工作。我看到我可以更改数字,以便宏在该特定表中工作。
  • @PMC11 不用担心。没错 - 您可以更改数字,或者如果您愿意,可以遍历文档中的所有表格。
  • @Dick Kusleika 非常感谢您的所有帮助和如此迅速的回复!我唯一的问题是让这个宏使用 RGB 颜色而不是 wdColorIndex。您能否就此提供任何指示?
猜你喜欢
  • 2013-10-18
  • 1970-01-01
  • 1970-01-01
  • 2022-01-20
  • 2014-01-05
  • 1970-01-01
  • 2019-12-18
  • 2017-12-27
  • 2016-02-21
相关资源
最近更新 更多