2

I'm trying to automatically start a macro based on the value entered into a cell. I was able to do it for one cell but how can I apply it to a range, example from L1 to L600?

Here is the code that works for 1 cell:

Sub Worksheet_Change(ByVal Target As Range)

Dim CAD As String
CAD = "Canadians (CDN)"

    If Intersect(Target, Range("L14")) Is Nothing Then Exit Sub
    Application.EnableEvents = False 'to prevent endless loop

        If Range("L14").Value = CAD Then
        Range("M14") = 1
        End If

    Application.EnableEvents = True

End Sub

Basically I have to check the next cell L15 and enter a value in M15 if the condition is met and so on....

Lance Roberts
  • 22,383
  • 32
  • 112
  • 130
Seva
  • 57
  • 10

2 Answers2

4

I see Sid has already posted an answer, but here's a slightly different version:

Sub Worksheet_Change(ByVal Target As Range)

Dim CAD As String, c as Range, rng As Range
CAD = "Canadians (CDN)"

on error goto haveErr
    set rng = application.Intersect(Target, Me.Range("L1:L600"))
    if not rng is nothing then
        Application.EnableEvents = False         
        for each c in rng.cells
           if c.value=CAD then c.offset(0,1).value=1
        next c
    End If

haveErr:
    Application.EnableEvents = True

End Sub
Tim Williams
  • 154,628
  • 8
  • 97
  • 125
  • 1
    `set rng = application.Intersect(Target, Me.Range("M1:M600"))` You meant `set rng = application.Intersect(Target, Me.Range("L1:L600"))` I guess? – Siddharth Rout Nov 05 '13 at 22:42
3

Is this what you are trying (UNTESTED)?

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim CAD As String: CAD = "Canadians (CDN)"

    If Target.Cells.CountLarge > 1 Then Exit Sub

    On Error GoTo Whoa

    Application.EnableEvents = False

    If Not Intersect(Target, Range("L1:L600")) Is Nothing Then
        If Target.Value = CAD Then Target.Offset(, 1).Value = 1
    End If

Letscontinue:
    Application.EnableEvents = True
    Exit Sub
Whoa:
    MsgBox Err.Description
    Resume Letscontinue
End Sub

And since you are using Worksheet_Change you may want to see this POST as well.

Community
  • 1
  • 1
Siddharth Rout
  • 147,039
  • 17
  • 206
  • 250