如果单元格A为空,则清除B列的单元格 - RANGE

时间:2016-03-29 23:58:01

标签: excel excel-vba vba

遇到问题并寻求建议。我一直在Excel中使用下面的代码一段时间,如果单元格A为空,它会清除B列的内容。它工作得很好,但我现在需要它在特定范围内工作(A6:B35)。有什么想法吗?

Private Sub Worksheet_Change(ByVal Target As Range)
On Error Resume Next
If Target.Column = 1 Then
If Target.Validation.Type = 3 Then
Application.EnableEvents = False
Target.Offset(0, 1).ClearContents
End If
End If

exitHandler:
Application.EnableEvents = True
Exit Sub

End Sub

2 个答案:

答案 0 :(得分:1)

您需要测试活动单元格(目标)是否落在A6:A35范围内。像这样:

Private Sub Worksheet_Change(ByVal Target As Range)
On Error Resume Next
If not intersect(target, range("A6:A35")) is nothing then
   If Target.Validation.Type = 3 Then
      Application.EnableEvents = False
      Target.Offset(0, 1).ClearContents
      Application.EnableEvents = True
   End If
End if
exitHandler:

End Sub

您还应该缩进代码,使其更具可读性。它将有助于循环和IF语句。

答案 1 :(得分:0)

类似

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

Set rng1 = Intersect(Target, Range("A6:B35"))

If rng1 Is Nothing Then Exit Sub

Application.EnableEvents = False
For Each rng2 In rng1
    If rng2.Validation.Type = 3 Then rng2.Offset(0, 1).ClearContents
Next
Application.EnableEvents = True

End Sub