使用Word VBA根据单元格值为表格中的单元格着色

时间:2016-03-23 11:21:43

标签: vba ms-word word-vba

在Word中,我有一个包含多个数据表的文档。隐藏在这些单元格内部(视图之外,但数据存在)是我想要遮蔽单元格的颜色的十六进制代码。我之所以选择十六进制值只是因为它相对较短而且它是一个独特的文本,不会与单元格中的其他文本混淆。

我发现在线修改了一些代码,但我似乎无法使其正常工作。它没有任何错误,只是没有任何反应。我觉得问题在于搜索表格中的文本值,但我花了好几个小时,我觉得我现在很困惑!

Sub ColourIn()

Dim oTbl As Table
Dim oCel As Cell
Dim oRng As Range
Dim oClr As String

For Each oTbl In ActiveDocument.Tables
For Each oCel In oTbl.Range.Cells
Set oRng = oCel.Range
oRng.End = oRng.End - 1

If oRng = "CCFFCC" Then
oCel.Shading.BackgroundPatternColor = wdColorLightYellow
End If
If oRng = "FFFF99" Then
oCel.Shading.BackgroundPatternColor = wdColorPaleBlue
End If

Next
Next
End Sub

谢谢!

编辑:

我也试过这个代码,结果没有发生任何结果:

Sub EachCellText()

Dim oCell As Word.Cell
Dim strCellString As String

For Each oCell In ActiveDocument.Tables(1).Range.Cells
strCellString = Left(oCell.Range.Text, _
Len(oCell.Range.Text) - 1)

If strCellString = "CCFFFF" Then
oCell.Shading.BackgroundPatternColor = wdColorLightGreen
If strCellString = "CCFFCC" Then
oCell.Shading.BackgroundPatternColor = wdColorLightYellow
If strCellString = "FFFF99" Then
oCell.Shading.BackgroundPatternColor = wdColorPaleBlue

End If
End If
End If

Next
End Sub

1 个答案:

答案 0 :(得分:0)

您的代码无处可去。但是你正在检查整个Cell值与十六进制代码,这不起作用,因为“blablabla FFFFFF”永远不会等于“FFFFFF”。所以你必须检查Hex代码是否在Cell值中:

Sub ColourIn()

Dim oTbl As Table
Dim oCel As Cell
Dim oRng As Range
Dim oClr As String

For Each oTbl In ActiveDocument.Tables

    For Each oCel In oTbl.Range.Cells

        Set oRng = oCel.Range
        oRng.End = oRng.End - 1

        Dim cellvalue As String

        'check if Colorcode is in cell
        If InStr(oRng, "CCFFCC") Then

            'Set Cell color
            oCel.Shading.BackgroundPatternColor = wdColorLightYellow

            'Remove Colorcode from Cell
            cellvalue = Replace(oRng, "CCFFCC", "")

            'load new value into cell
            oRng = cellvalue
        End If
    Next
Next
End Sub

现在你只需要添加你想要使用的所有颜色(我更喜欢Select Case语句),代码应该可以正常工作