【问题标题】:Using VBA to change color of single word in string of Word document table to match cell color使用VBA更改Word文档表格字符串中单个单词的颜色以匹配单元格颜色
【发布时间】:2019-06-05 03:13:02
【问题描述】:

我的 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

我的期望是,当在任何单元格中找到单词时,代码的.Replacement部分会将单词颜色更改为backColor变量值,但文本颜色不会改变。

【问题讨论】:

    标签: vba ms-word


    【解决方案1】:

    我认为您面临的问题是您的单元格颜色未设置为任何颜色,并且使用默认颜色 -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
    ...
    

    否则,如果背景上设置了任何颜色,它将使用它。

    【讨论】:

    • 单元格颜色由用户设置(通常为非白色阴影)。因此,在一个实例中,一行单元格是灰色阴影,backColor 值为 -603923969。我会添加这个......今天我尝试再次运行代码并且它只是工作。我不记得在昨天没有工作之前更改过任何东西,所以我认为它已经完成了。
    • 好吧,这是我的猜测,因为这是唯一一次您的代码在我的测试中无法“工作”。不过很高兴为您解决。
    猜你喜欢
    • 1970-01-01
    • 2018-06-02
    • 1970-01-01
    • 2016-08-20
    • 1970-01-01
    • 2016-10-06
    • 2015-01-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多