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

Macro with show messsage box if cell contains value

我想做一个宏。我的测试单元在另一个 sheet 上。 Sheet -(数据)宏检查范围 ("D2:D10") 如果单元格包含值 12 如果是,则显示消息框 "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

下面的代码将更正您的代码(它将 运行 没有错误):

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 事件("data" sheet)中想要实现的目标。

代码

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