3

我正在尝试制作一个在单元格更新时自动执行的小型 Excel 宏:

Private Sub Worksheet_Change(ByVal Target As Range)

    If Target.Value = "N/A" Then
        Target.Interior.Color = RGB(205, 201, 201)
    End If

    If Target.Value = "Pass" Then
        Target.Interior.Color = RGB(0, 255, 0)
    End If

    If Target.Value = "Fail" Then
        Target.Interior.Color = RGB(255, 0, 0)
    End If

End Sub

但是,当我尝试在多个其他单元格中复制和粘贴任何单元格时,我收到此错误:

运行时错误“13”:类型不匹配。

为什么会这样,我该如何解决?

4

1 回答 1

4

因为在这种情况下,您在Target. 试试这个代码

我已禁用Events,因为这是使用时的好习惯Worksheet_Change- 即使单元格颜色更改不会重新触发事件

Private Sub Worksheet_Change(ByVal Target As Range)
Dim rng1 As Range

With Application
.EnableEvents = False
.ScreenUpdating = False
End With

For Each rng1 In Target.Cells
   Select Case rng1.Value
   Case "N/A"
    Target.Interior.Color = RGB(205, 201, 201)
   Case "Pass"
      Target.Interior.Color = RGB(0, 255, 0)
       Case "Fail"
      Target.Interior.Color = RGB(255, 0, 0)
    End Select
Next

With Application
.EnableEvents = True
.ScreenUpdating = True
End With

End Sub
于 2013-03-25T09:29:53.260 回答