1
votes

I have 5 columns ((a)uptick, (b)downtick, (c)original, (d)current), and (e) Stored Value. All columns need to be a range of rows. When d2 changes I want to compare it to e2 and if d2>e2 then bump the counter in a2 by 1 (uptick), if d2<e2 then bump the counter in b2 (downtick). I have it working with many if and elseif statements but would rather use less code using variables for the range. To detect the changing cell I use "If Not Intersect (Target, Range("d2:d10")) Is Nothing Then...."

I cannot seem to figure out how to replace specific cell references with ranges. Any help would be most appreciated!

Sample Code below not using ranges yet.

Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Range("D2:D10")) Is Nothing Then
    If Target.Value > Range("E2") Then
    Range("A2") = Range("A2") + 1
    Pause 2#
    Range("E2") = Target.Value
    ElseIf Target.Value < Range("E2").Value Then
    Range("B2") = Range("B2") + 1
    Pause 2#
    Range("E2") = Target.Value
    End If
    End If
End Sub
2

2 Answers

0
votes

I assume you want to change the cell value in the same row that the value was entered in column D, i.e. if D4 has been changed, then adjust A4 or B4. To do that, you need the row number of the changed cell. You can extract that with target.row. Throw that into a variable and use the variable instead of the row number in the Range() property.

Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Range("D2:D10")) Is Nothing Then
      dim myRow as long
      myRow = target.row
      If Target.Value > Range("E" & myRow) Then
        Range("A" & myRow) = Range("A" & myRow) + 1
        Pause 2#
        Range("E" & myRow) = Target.Value
      ElseIf Target.Value < Range("E" & myRow).Value Then
        Range("B" & myRow) = Range("B" & myRow) + 1
        Pause 2#
        Range("E" & myRow) = Target.Value
      End If
    End If
End Sub
0
votes

You could use .Offset to get the same result. The following code assumes you're only interested in the range D2:D10 and aren't concerned if the value in column D equals the value in column E.

Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Range("D2:D10"), Target) Is Nothing Then
    If Target.Rows.Count > 1 Then Exit Sub
        If Target > Target.Offset(, 1) Then
            Target.Offset(, -3) = Target.Offset(, -3) + 1
            Else
            If Target < Target.Offset(, 1) Then
                Target.Offset(, -2) = Target.Offset(, -2) + 1
            End If
        End If
End If
End Sub