簡體   English   中英

使用VBA更改Word文檔表的字符串中單個單詞的顏色以匹配單元格顏色

[英]Using VBA to change color of single word in string of Word document table to match cell color

我有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變量值,但文本顏色不會更改。

我認為您面臨的問題是您的單元格顏色未設置為任何內容,並且處於默認顏色-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
...

否則如果背景上有任何顏色設置,它將使用它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM