Forum Discussion
VBA code just looping despite exit subs
It's been many, many years since I last dabbled with VBA in Excel.
I am trying to put some text in I3 when I change a Data Validation List depending on its value. There are a number of values, but my code only looks for NONE, an empty cell (delete the contents), and the rest are weapons.
The is a single If Then Elseif Else block. Regardless of what I do, I can't get it to exit to exit the sub and keeps looping. It fills I3 with "Selection is Selection is...until Excel crashes.
Here's what Ive got:
Private Sub Worksheet_Change(ByVal Target As Range)
If (Target.Address = "$B$3" And Target.Value = "NONE") Then
Range("I3").Value = "Selection is " & Target.Value & ". You have no Melee weapon."
Exit Sub
ElseIf Target.Value = "" Then
Exit Sub
Else
Range("I3").Value = "Selection is " & Target.Value & ". This is a Melee Weapon."
Exit Sub
End IfExit Sub
End Sub
1 Reply
- NikolinoDEPlatinum Contributor
This is a classic Worksheet_Change trap, and your Exit Subs are not the problem π
itβs looping becourse Worksheet_Change fires every time any cell on the sheet changes.
Your code:
- User changes B3 β event fires
- Your code writes to I3 β event fires again
- That second trigger writes to I3 again, appending text
- Repeat until Excel crashes
So even though you Exit Sub, the act of writing to I3 retriggers the event.
Two required fixes
Only respond when B3 changes
Disable events while writing to I3
Corrected, safe version of your code:
Private Sub Worksheet_Change(ByVal Target As Range) ' Only run when B3 changes If Target.Address <> "$B$3" Then Exit Sub Application.EnableEvents = False If Target.Value = "NONE" Then Range("I3").Value = "Selection is " & Target.Value & ". You have no Melee weapon." ElseIf Target.Value = "" Then Range("I3").ClearContents Else Range("I3").Value = "Selection is " & Target.Value & ". This is a Melee Weapon." End If Application.EnableEvents = True End SubPrevents changes to I3 from retriggering logic.
Stops Excel from firing Worksheet_Change while your code edits cells.
My answers are voluntary and without guarantee!
Hope this will help you.
Was the answer useful? Mark as best response and like it!
This will help all forum participants.