Home » excel » excel – Appending text to cell but stuck in loop

excel – Appending text to cell but stuck in loop

Posted by: admin May 14, 2020 Leave a comment

Questions:

My problem is that my code doesn’t work how I think it should work. I have Loop in my worksheet_change macro, and in that loop I want that if statement is correct (MsgBox button pressed Yes), what is written in that cell would have appended value at the end of that text.

But if I run this macro and I press Yes – cell value has the value at the end, but MsgBox comes right again, and I’m stuck in that loop… I’m new to VBA programming and syntax.

Can someone help me and explain my mistake?

Code:

Private Sub Worksheet_Change(ByVal Target As Range)

Dim rLockable As Range
Dim cl As Range

Set rLockable = Range("C13:J1000")
Set cl = Range("C13:J1000")
Set cele = Range("K13:K1000")
vardas = ActiveWorkbook.Sheets("Login").Range("O8").Value

Select Case True
    Case Not Intersect(rLockable, Target) Is Nothing
        'If target is within the range then do nothing
        If Intersect(rLockable, Target) Is Nothing Then Exit Sub
        ActiveSheet.Unprotect Password:="1234"
        For Each cl In Target
            If cl.Value <> "" Then
                check = MsgBox("Ar áraðyti áraðà? Koreguoti áraðo nebegalësite.", vbYesNo, "Áraðo iðsaugojimas")
                If check = vbYes Then
                    Target.Worksheet.Unprotect Password:="1234"
                    cl.MergeArea.Locked = True
                    cl.Value = cl.Value & " " + vardas
                Else
                    cl.Value = ""
                    ActiveSheet.Protect Password:="1234"
                End If
            End If
            Exit For
        Next cl

    Case Not Intersect(Range("K13:K1000"), Target) Is Nothing
        ActiveSheet.Unprotect Password:="1234"
        For Each cele In Target
            If cele.Value <> "" Then
               cele.Offset(0, 2).MergeArea.Value = vardas
            End If
            Exit For
        Next cele
End Select

ActiveSheet.Protect Password:="1234"

End Sub
How to&Answers:

Before making a change to the worksheet you need to set enableEvent to false or the worksheet_change event will kick in again.

application.enableEvents=false
'change the worksheet
application.enableEvents=true
'resets the worksheet_change event