我有Word文档,其中包含具有颜色编码单元格的表格,我想通过更改其颜色以匹配单元格颜色来"隐藏"每个单元格的某些单词。
我有一个VBA脚本,可以从数组列表中搜索单词并成功找到它们,但是我无法让这些单词将颜色更改为单元格背景颜色。
Sub TableWordColorReplace()
Dim C As Cell
Dim tableCount As Long
Dim Ctr As Integer
Dim backColor As Long
Dim i As Long
Dim range As range
Dim TargetList
tableCount = ActiveDocument.Tables.Count 'to account for any/all tables in the document
TargetList = Array("word1", "word2", "word3")
For Ctr = 1 To tableCount 'cycle thru each table in the document
For Each C In ActiveDocument.Tables(Ctr).range.Cells 'search in every cell in the table
backColor = C.Shading.BackgroundPatternColor 'the color I want to change the found text to
For i = 0 To UBound(TargetList) 'cycle thru each word in the list
With C.range.Find
.Text = TargetList(i)
With .Replacement
.Text = TargetList(i)
.ClearFormatting
.Font.Color = backColor 'this is where I expect the word color to change, but it doesn't
End With
.Execute Replace:=wdReplaceAll
End With
Next
Next C
Next Ctr
End Sub
我的期望是,当在任何单元格中找到该单词时,.代码的替换部分会将单词颜色更改为 backColor 变量值,但文本颜色不会更改。
我认为您面临的问题是您的单元格颜色未设置为任何内容,并且在默认颜色-16777216
(与wdColorAutomatic
相同(,您正在为文本设置自动颜色(通常是黑色(。
如果您的单元格背景始终为白色,则可以执行.Font.Color = wdColorWhite
,否则您可以检查默认值,即:
...
backColor = C.Shading.BackgroundPatternColor 'the color I want to change the found text to
If backColor = -16777216 Then backColor = wdColorWhite
...
否则,如果背景上设置了任何颜色,它将使用该颜色。