0

Hello i have problems with my vba code. everithing works as expected until it jumps from the last row "End sub" to A or B instead of stopping the code.

Private Sub Worksheet_Change(ByVal Target As Range)
Dim LR As Long
LR = Cells(1, 1).End(xlDown).Row 'first empty row
lRow = Cells(Rows.Count, 1).End(xlUp).Row 'last row
'Find "Titel"
    For A = 2 To lRow
        If Cells(A, 1).Value Like "Titel" Then
        LRT = A ' Row number with "Titel"
        Exit For
        End If
    Next A

If Not Application.Intersect(Range("A2:G" & LRT - 1), Range(Target.Address)) Is Nothing Then
    For b = 2 To LRT - 1
        If Cells(b, 1).Value = "" Then
            If b <> LRT - 1 Then
                Rows(b).EntireRow.Delete
            End If                  'A: if row is deleted above empty row above "Titel"
                                    'LRT & A increased by1; b decreased by 1; LR=LR; lRow increased by 1
        End If
    Next b
    If Cells(LRT - 1, 1) <> "" Then
        Rows(LRT).EntireRow.Insert
    End If                  'B: if something is added in the empty row above "Titel"
                            'LRT & b & A decreased by 1; LR increased by 5; lRow decreased by 1

End If

End Sub ' Jumps after this to A or B

My program looks like this:

enter image description here

and I don't understand at all why all this is happening. I have written its behavior in the comments.

protter
  • 129
  • 5
  • 6
    What's really happening is that with EVERY change you make to the worksheet -- example: `Rows(b).EntireRow.Delete` -- a `Worksheet_Change` event is fired to call the sub again. So you're constantly re-calling the `Worksheet_Change` sub from within the sub recursively. My suggestion is to [disable/enable events](https://stackoverflow.com/a/10023082/4717755) around that section of code so you're only going into the sub once. – PeterT Sep 23 '21 at 18:31

0 Answers0