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

When did Power Query debut in Excel?
Although it was an add-in in Excel 2010 & Excel 2013, Power Query became a part of Excel in 2016, in Data, Get & Transform Data.
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,214,641
Messages
6,120,688
Members
448,978
Latest member
rrauni

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