Excel VBA WorkSheet_Change清除内容如果为空

时间:2016-10-06 04:40:32

标签: excel vba excel-vba

我设置Worksheet_Change宏,以便如果单元格K4的内容不等于"基于事件" J5:K7的内容被清除。这非常有效。代码如下。

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim MRange As Range

    Set MRange = Range("K4")
    If MRange <> "Event Based" Then
       If Union(Target, MRange).Address = MRange.Address Then
           Application.EnableEvents = False
           Range("J5:K7").Select
           Selection.ClearContents
           Application.EnableEvents = True
       End If
    End If

End Sub

但是如果清除了单元格J12的内容,我想要Worksheet_Change事件。但是下面的宏不起作用。我知道这与细胞价值是空的有关,但我会感激任何帮助。

    Dim NRange As Range

    Set NRange = Range("J12")
    If NRange = "" Then
        If Union(Target, NRange).Address = NRange.Address Then
            Application.EnableEvents = False
            Range("J5:K7").Select
            Selection.ClearContents
            Application.EnableEvents = True

        End If
    End If

End Sub

1 个答案:

答案 0 :(得分:1)

以下代码检查Cell J12值是否已更改,如果单元格值为&#34;&#34;然后它清除Range&#34; J5:K7&#34;。

的内容
Private Sub Worksheet_Change(ByVal Target As Range)

    Dim IntersectRange              As Range
    Dim NRange                      As Range

    Set NRange = Range("J12")
    Set IntersectRange = Intersect(Target, NRange)

    ' continue running this code only if Cell J12 has changed
    If Not IntersectRange Is Nothing Then

        If Target.Value = "" Then
            Application.EnableEvents = False
            Range("J5:K7").ClearContents
            Application.EnableEvents = True
        End If

    End If

End Sub
相关问题
最新问题