我是VBA的新手,所以我正在努力解决看似简单的任务。
我在word文档的每个单元格中都有几行文本。每个单元格包含一个类别" Science"或者"健康"或其他几个。在那一刻我实际上只是使用了一个特殊的角色,如" *"或" @"用于测试目的。
我需要更改单元格中所有文本的文本颜色,具体取决于单元格中的类别。所以txt将是例如绿色为"科学" "健康"。
运行宏似乎是进行这些更改的最快方式(在我的最终文档中将有超过200个这样的单元格并且手动着色是浪费时间)。基本上,我一直在努力改变单元格中所有文本的颜色,其次,如果不满足第一个标准,如何再次进行宏搜索。我想1个宏可以完成整个文档的着色,而不是为我需要的每种颜色都有多个宏。
如果你能给我一些我可以使用的VBA的例子,那将是最有帮助的。我真的很挣扎,你能给予的任何帮助都会给我和我的团队节省很多时间。
答案 0 :(得分: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 = Array(RGB(192, 192, 192), RGB(188, 25, 67))
以及将颜色设置为
的行cll.Range.Font.TextColor.RGB = Colors(i)