Home » excel » Excel VBA Target.address worksheet.onchange infinite loop

Excel VBA Target.address worksheet.onchange infinite loop

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have cell A1, cell B1 and cell C1, I need check if value changed in A1 by user or by VBA. Whith out If statment on Target.Address A1 makes infinite loop

Private Sub Worksheet_Change(ByVal Target As range)

If Target.Address = B1 or Target.Address = C1 Then
    If IsEmpty(Cell("B1")) then
        Cell("A1").value = "Enter value"
            If IsEmpty(Cell("C1")) then
                Cell("A1").value = ""
            Else
                Cell("A1").value = "=C1/B1"
            End IF
    End IF
End IF


If Target.Address = A1
    IF "changed by user typing" Then
       Cell("B1").value = ""
       Cell("C1").value = ""
    Else
    End IF
End IF
End Sub

How to determine what Target was changed by user not from VBA?

How to&Answers:

I suspect you want something like this:

Private Sub Worksheet_Change(ByVal Target As Range)

    If Not Intersect(Target, Range("A1")) Is Nothing Then
        Application.EnableEvents = False
        Range("B1:C1").Value = ""
        Application.EnableEvents = True
    ElseIf Not Intersect(Target, Range("B1:C1")) Is Nothing Then
        Application.EnableEvents = False
        If IsEmpty(Range("B1")) Then
            Range("A1").Value = "Enter value"
        ElseIf IsEmpty(Range("C1")) Then
            Range("A1").Value = ""
        Else
            Range("A1").Value = "=C1/B1"
        End If
        Application.EnableEvents = True
    End If

End Sub