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

我想做一个macros。 我的testing单元在另一张纸上。 工作表 – (数据)macros如果单元格中包含值12,则检查一个范围("D2:D10") ,如果是,则显示一个消息框"Go to add to system"并且此单元格中的macrosfind的值将设置为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事件(“数据”工作表)中实现的内容。

 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