更改单元格背景颜色时键入不匹配

时间:2015-03-12 11:23:30

标签: vba ms-word

我尝试根据下拉字段的值更改单元格的颜色。 这是我的代码。

Sub ChangeCellColor()
Dim MyTable As Table
Set MyTable = ActiveDocument.Tables(1)
Dim CellStatus As String
Dim CellColor As String
CellStatus = ActiveDocument.FormFields("DropdownStatus").DropDown.Value
Select Case CellStatus
    Case 2
        CellColor = "wdRed"
    Case 3
        CellColor = "wdYellow"
    Case 4
        CellColor = "wdGreen"
End Select
MyTable.Cell(1, 1).Shading.BackgroundPatternColor = CellColor
MsgBox CellColor
End Sub

我总是在行

上遇到类型不匹配错误
MyTable.Cell(1, 1).Shading.BackgroundPatternColor = CellColor

2 个答案:

答案 0 :(得分:1)

您正尝试将BackgroundPatternColor属性设置为字符串。它需要设置为WdColor常量。

Dim CellColor As WdColor
Case 2
    CellColor = wdRed 'Remove the quotes

请参阅https://msdn.microsoft.com/en-us/library/office/aa223960(v=office.11).aspx

答案 1 :(得分:0)

由于使用String而不是wdColor,您的类型不匹配,请尝试以下操作:

Sub ChangeCellColor()
Dim MyTable As Table
Set MyTable = ActiveDocument.Tables(1)
Dim CellStatus As String
Dim CellColor As wdColor
CellStatus = ActiveDocument.FormFields("DropdownStatus").DropDown.Value
Select Case CellStatus
    Case 2
        CellColor = wdRed
    Case 3
        CellColor = wdYellow
    Case 4
        CellColor = wdGreen
End Select
MyTable.Cell(1, 1).Shading.BackgroundPatternColor = CellColor
MsgBox CellColor
End Sub
相关问题