我正在尝试制作一个在单元格更新时自动执行的小型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': 类型不匹配。
为什么会这样,我该如何解决?
答案 0 :(得分: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