如果单元格包含值,则显示消息框的宏

时间:2016-12-12 08:17:45

标签: excel vba excel-vba macros msgbox

我想做一个宏。我的测试单元在另一张纸上。工作表 - (数据)如果单元格包含值12,则宏检查范围("D2:D10")如果是,则显示消息框"Go to add to system",并且宏发现值的此单元格将设置为0.

我有这个代码,但它对我不起作用我不知道为什么。你能帮助我吗?

Private Sub check(ByVal Target As Range)
For Each c In Worksheet("data").Range("D2:D10")
 If Range("D2:D10") = 12 Then
    MsgBox "Go to add to system"
    Range ("D2:D10").value = 0
 End If
Next c
End Sub

1 个答案:

答案 0 :(得分:1)

下面的代码将更正您的代码(它将正常运行):

Option Explicit

Private Sub check(ByVal Target As Range)

Dim c   As Range

For Each c In Worksheets("data").Range("D2:D10")
    If c.Value = 12 Then
        MsgBox "Go to add to system"
        c.Value = 0
    End If
Next c

End Sub

但是,您可以采用稍微不同的方法 - 在Worksheet_Change事件中完成您要实现的目标("数据"表格)。

<强>代码

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)

Dim c   As Range

' Optional : use if criteria below to check the range only
' if one of the cells inside range("D2:D10") has changed
If Not Intersect(Range("D2:D10"), Target) Is Nothing Then
    ' if you decide to use the "If"above, then you don't need the "For" loop below
    For Each c In Range("D2:D10") 
        If c.Value = 12 Then
            MsgBox "Go to add to system"
            c.Value = 0
        End If
    Next c
End If

End Sub