Prevent Code from running on cell change

seguin85

Active Member
Joined
Mar 17, 2015
Messages
278
Office Version
  1. 365
Platform
  1. Windows
Hi All,

I have the following code that works great:

Code:
Private Sub Worksheet_Change(ByVal target As Range)
If Not Intersect(target, Range("M21:M6000")) Is Nothing Then

On Error Resume Next

If target.Cells.Count > 1 Or IsEmpty(target) Then Exit Sub

    Dim countIN As Integer

    countIN = Application.WorksheetFunction.CountIf(Range("M21:M6000"), "*Inquiry*")

    If target.Cells Like "*Inquiry*" Or target.Cells Like "*inquiry*" Then
    
         target.Cells = "Inquiry " & countIN

    End If

End If

End Sub

The problem is that it seems to run again and again since the target cell is changing. Is there a way to only allow the code to run once?
 

Excel Facts

Excel Wisdom
Using a mouse in Excel is the work equivalent of wearing a lanyard when you first get to college
The piece you are missing is Application.EnableEvents you set it to FALSE before the code that changes the sheet and back to TRUE after. You also have an extra End If in there, although I would do the second on one line as well.
Code:
Private Sub Worksheet_Change(ByVal target As Range)
If Not Intersect(target, Range("M21:M6000")) Is Nothing Then
On Error Resume Next
If target.Cells.Count > 1 Or IsEmpty(target) Then Exit Sub
Dim countIN As Integer
Application.EnableEvents = False
countIN = Application.WorksheetFunction.CountIf(Range("M21:M6000"), "*Inquiry*")
If target.Cells Like "*Inquiry*" Or target.Cells Like "*inquiry*" Then target.Cells = "Inquiry " & countIN
Application.EnableEvents = True
End Sub
 
Last edited:
Upvote 0

Forum statistics

Threads
1,215,348
Messages
6,124,425
Members
449,157
Latest member
mytux

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top