设置整行的颜色时,应用程序定义或对象定义的错误

我有这个曾经工作的小程序,但现在不行。 我不知道我做了什么。 这是worksheet_selection子集,所以无论何时导航到活动工作表中的其他单元格或单元格中的一个单元格发生更改时都会运行。 它所做的就是检查是否select了一定范围的单元格,如果是,则会更改整行(绿色,黄色或白色)。 只要我点击一个目标单元格,就会得到“应用程序定义或对象定义的错误”。 请参阅下面的代码。 有人可以帮帮我吗? 提前致谢。

码:

Private Sub Worksheet_SelectionChange(ByVal Target As Range) If Target.row = 2 Or Target.row = 4 Or Target.row = 6 Or Target.row = 8 Or Target.row = 10 Or Target.row = 12 Or Target.row = 14 Or Target.row = 16 Or Target.row = 18 Then With Target.EntireRow.Interior If .Color = 16777215 Then 'white .Color = 65280 'green ' this is where the error is given ElseIf .Color = 65280 Then ' green .Color = 65535 'yellow ElseIf .Color = 65535 Then 'yellow .Color = -4142 End If End With End If End Sub 

如果您的工作表受到保护 ,就会得到这个结果。

因此,无论是在更改颜色之前解锁工作表,还是将工作表保护方法更改为.Protect UserInterfaceOnly:=True

你也得到了不想要的结果,用你现在的代码 – 试着突出显示一些行上的多个单元格,不pipe是从2/4/6/8/10/12/14/16/18行开始还是结束!

尝试了解如下:

 Option Explicit Private Const C_WHITE As Long = 16777215 ' white Private Const C_GREEN As Long = 65280 ' green Private Const C_YELLOW As Long = 65535 ' yellow Private Const C_NONE As Long = xlNone ' No Fill Private Sub Worksheet_SelectionChange(ByVal Target As Range) Dim oRng As Range, oRngApplicable As Range Set oRngApplicable = Intersect(Target.Columns(1), Target.Worksheet.Rows("2:18")) If oRngApplicable Is Nothing Then Exit Sub For Each oRng In oRngApplicable If oRng.Row Mod 2 = 0 Then With oRng.EntireRow.Interior Select Case .Color Case C_WHITE: .Color = C_GREEN Case C_GREEN: .Color = C_YELLOW Case C_YELLOW: .Color = C_NONE End Select End With End If Next End Sub