我有一个从另一个程序生成的 Word 文档,并且“突出显示”单元格是使用黄色单元格背景创建的。
此行为无法更改。另外,我需要将表格复制到的程序无法识别背景颜色。
我正在尝试将任何黄色背景的单元格更改为红色文本/字体颜色。
Sub Highlight()
'
' Highlight Macro
' Applies color highlighting to the selection
'
Dim Tbl As Table
Dim i As Integer, j As Integer
For Each Tbl In ActiveDocument.Tables
For j = 1 To Tbl.Columns.Count
For i = 1 To Tbl.Rows.Count
If Not (Tbl.Cell(i, j).Shading.BackgroundPatternColor = wdColorAutomatic) Then Tbl.Cell(i, j).Range.Font.ColorIndex = wdRed
Next
Next
Next
End Sub
这会更改一些单元格(显然是标题行和第一列),但会跳过所有其他单元格并生成错误:
所请求的集合成员不存在。
它指向线:
If Not (Tbl.Cell(i, j).Shading.BackgroundPatternColor = wdColorAutomatic)
我认为问题在于表格有一些合并的单元格,而行/列索引没有考虑到这一点。如何解释合并单元格?
值得注意的是,所有感兴趣的单元格都位于没有合并单元格的行中 - 这意味着如果我可以(1)忽略合并单元格或(2)首先运行检查以确保单元格存在,我认为我的问题将得到解决.
避免拆分/合并单元格的问题:
Sub Highlight()
Dim Tbl As Table, C As Cell
For Each Tbl In ActiveDocument.Tables
For Each C In Tbl.Range.Cells
If C.Shading.BackgroundPatternColor <> wdColorAutomatic Then
C.Range.Font.ColorIndex = wdRed
End If
Next
Next
End Sub