VBA:自动清除基于单元格值的整行

时间:2015-09-03 17:48:39

标签: excel vba excel-vba

基本上,我有一个宏,当一个值放在B列的单元格中时,它会更新其他列中的其余信息。当我在B列中删除该值时,我希望删除其他列中的其余信息。

我使用的代码类似于以下代码:

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

    Set KeyCells = Range("B:B")

        If Not Application.Intersect(KeyCells, Range(Target.Address)) _
               Is Nothing Then

           If Range(Target.Address).Value = "X" Then
              Range(Target.Address).Offset(0, 1).Value = "1"
              Range(Target.Address).Offset(0, 2).Value = "2"
              Range(Target.Address).Offset(0, 3).Value = "3"
              Range(Target.Address).Offset(0, 4).Value = "4"
              End If
        EndIf

End Sub

漫长的方法是做另一个if语句:

 If Range(Target.Address).Value = "" Then
   Range(Target.Address).Offset(0, 1).Value = ""
   Range(Target.Address).Offset(0, 2).Value = ""
   Range(Target.Address).Offset(0, 3).Value = ""
   Range(Target.Address).Offset(0, 4).Value = ""
   End If

由于宏自动运行,这将完成工作。有没有办法用clear.contents做到这一点?

1 个答案:

答案 0 :(得分:0)

所以我会这样做:

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Column = 2 Then
        If Target.Value = "x" Then
            Target.Offset(0, 1) = "1"
            Target.Offset(0, 2) = "2"
            Target.Offset(0, 3) = "3"
            Target.Offset(0, 4) = "4"
        Else
            Range(Target.Offset(0, 1), Target.Offset(0, 4)).ClearContents
        End If
     End If
End Sub