从单元格中删除值时键入不匹配

时间:2015-01-05 14:25:24

标签: excel vba type-mismatch

我对VBA很新,并且遇到了一个非常令人沮丧的错误。我的代码试图根据其他单元格的值锁定和消隐单元格。但是,如果删除工作表中的任何单元格,代码会中断,我会收到类型不匹配错误。如果更改单元格的值,则代码不会中断,只有在删除时才会中断。

我的代码在下面提供,是否有人有想法?在此先感谢!!

Private Sub Worksheet_Change(ByVal Target As Range)
  If Target <> Range("$C$28") And Target <> Range("$C$31") Then Exit Sub

  ActiveSheet.Unprotect

  If Range("C31") = "Cellular" And Range("C28") = "No" Then
    Range("C34").Locked = False
    Range("C34").Interior.ColorIndex = 19
    Range("C35").Locked = True
    Range("C35").Interior.ColorIndex = 1
    Range("C35").Value = "Verizon"
    Range("C37").Locked = False
    Range("C37").Interior.ColorIndex = 19
    Range("C38").Locked = False
    Range("C38").Interior.ColorIndex = 19

  ElseIf Range("C31") = "Cellular" And Range("C28") = "Yes" Then
    Range("C34").Locked = False
    Range("C34").Interior.ColorIndex = 19
    Range("C35").Locked = True
    Range("C35").Interior.ColorIndex = 1
    Range("C35").Value = "Verizon"
    Range("C37").Locked = True
    Range("C37").Interior.ColorIndex = 1
    Range("C37").Value = "Verizon"
    Range("C38").Locked = True
    Range("C38").Interior.ColorIndex = 1
    Range("C38").Value = "Verizon"

  ElseIf Range("C31") <> "Cellular" And Range("C28") = "No" Then
    Range("C34").Locked = True
    Range("C34").Interior.ColorIndex = 1
    Range("C34").Value = "Verizon"
    Range("C35").Locked = False
    Range("C35").Interior.ColorIndex = 19
    Range("C37").Locked = False
    Range("C37").Interior.ColorIndex = 19
    Range("C38").Locked = False
    Range("C38").Interior.ColorIndex = 19

  Else
    Range("C34").Locked = True
    Range("C34").Interior.ColorIndex = 1
    Range("C34").Value = "Verizon"
    Range("C35").Locked = False
    Range("C35").Interior.ColorIndex = 19
    Range("C37").Locked = True
    Range("C37").Interior.ColorIndex = 1
    Range("C37").Value = "Verizon"
    Range("C38").Locked = True
    Range("C38").Interior.ColorIndex = 1
    Range("C38").Value = "Verizon"

 End If

 ActiveSheet.Protect
End Sub

1 个答案:

答案 0 :(得分:0)

删除整行时,应确认生成的Target对象将代表整个行范围。因此,您的比较语句将失败,因为您依赖于范围对象的隐式/默认属性(其.Value属性)。尝试以这种方式引用此属性时,多单元格区域将引发错误。

所以你需要一些逻辑来避免这种情况。也许就像检查Target范围内的第一个单元格一样简单:

Private Sub Worksheet_Change(ByVal Target As Range)
  If Target.Cells(1,1) <> Range("$C$28") And Target <> Range("$C$31") Then Exit Sub