0

I would like to do a macro. My testing cells are on another sheet. Sheet - (data) Macro check a range ("D2:D10") if the cells contain value 12 if yes show me a message box "Go to add to system" and this cell where macro found a value will be set to 0.

I have this code but it doesn't work for me I don't known why. Can you help me?

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
Bojan B
  • 2,091
  • 4
  • 18
  • 26
Fiínek Cahů
  • 67
  • 1
  • 2
  • 11

1 Answers1

1

The code below will correct your code (it will run without errors):

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

However, you could go with a slightly different approach - by accomplishing what you are trying to achieve in the Worksheet_Change event (of "data" sheet).

Code

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
Shai Rado
  • 33,032
  • 6
  • 29
  • 51