Home » excel » excel vba on cell change error

excel vba on cell change error

Posted by: admin May 14, 2020 Leave a comment

Questions:
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Range = Range("A1") Then
    If Range("A1").Value <> Range("A2").Value Then
        Range("C1").Value = Range("C1").Value + 1
        Range("A2").Value = Range("A1").Value
    End If
End If
End Sub

that’s the code however when i copy paste a set off cell, let’s say 2 columns and 3 rows
it produce runtime error 13 type mismatch on line

If Target.Range = Range("A1") Then

why?
i simply wants the vba to do something everytime cell A1 changes
the value of A1 itself is an excel sum formula

How to&Answers:

You get type-missmatch error, becase you’re trying to compare range (containing many cells) with single cell. If you want to do something every time cell A1 changed, use this one instead:

Private Sub Worksheet_Change(ByVal Target As Range)
    Application.EnableEvents = False
    On Error GoTo ErrHandler

    If Not Intersect(Target, Range("A1")) Is Nothing Then
        If Range("A1").Value <> Range("A2").Value Then
            Range("C1").Value = Range("C1").Value + 1
            Range("A2").Value = Range("A1").Value
        End If
    End If

ExitHere:
    Application.EnableEvents = True
    Exit Sub
ErrHandler:
    Resume ExitHere
End Sub

also note that I’m using Application.EnableEvents = False – it’s a good habbit for Worksheet_Change event to use it. It prevents code from infinity firing itself each time you change any cell in event handler code.

UPD:

Btw, the value of A1 itself is an excel sum formula – you can’t track changes of formula using above approach. I covered in details how you can do it in this question: Using Worksheet_Calculate event for tracking changes of formula

Answer:

Simoco’s answer should work for you. Another way (the one I usually use, though only out of habit) is to compare the addresses:

Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Address = Range("A1").Address Then
    If Range("A1").Value <> Range("A2").Value Then
        Range("C1").Value = Range("C1").Value + 1
        Range("A2").Value = Range("A1").Value
    End If
End If
End Sub

Answer:

You are getting an error because Target.Range is not defined. You should either just refer to Target (a Range Object) or Target.Address (the address of the Range Object). Secondly, depending on the context, Range(“A1”) refers to either the cell A1 itself (a Range Object) or the value in cell A1 (a literal value). You need to carefully think what you want to compare to what.

If, as you said, you want the comparison done whenever the value in Range(“A1”) changes then you should follow Simoco’s suggestion.