Stop change event

gsnidow

New member
Joined
Aug 30, 2011
Messages
38
Reaction score
0
Points
0
Location
Virginia
Greetings all. I have a general question, so I don't think anyone will need to see the code. I have two cells, I'll call them cell1 and cell2. Cell1 is a date, and cell2 is a number. If someone changes the date in cell1, the change event references another sheet and populates the datediff in days in cell 2. This is working 100%. My problem is that I would like to put the same logic for changes to cell2, i.e. if someone changes the number, it will reference the same date in another sheet, and return the date that results from a date calculation, and populate that in cell1. I had this working 100% also. The problem is that I cannot have them both working, because it causes an unending loop of updates. Any ideas. I'm hoping someone knows something easy, if not I will post the code. Thank you.

Greg
 
Your change events are making changes, which cause the change event to be triggered.

The way I deal with this is:

Code:
Dim lEvents As Long  '<-- Put at top of module before any sub lines but after any option lines (if you have any)
Private Sub Worksheet_Change(ByVal Target As Range)
    lEvents = lEvents + 1
    If lEvents > 1 Then GoTo ExitPoint
    
    'Whatever you were doing goes here
    
ExitPoint:
    lEvents = lEvents - 1
End Sub

What that does is add 1 to a module level variable each time the code is run. If the variable is greater than 1, then none of your internal code is run. Before the procedure finished, it decreases the value again.

When the code starts initially, the value will be 0. It could trigger loops 100 times though, and wouldn't run the code after the first time until the original procedure ends.

Full article on it here: http://www.excelguru.ca/content.php...Properties-Are-Toggled-and-Controlling-Events
 
Thank you Ken, that seems to be working. I messed around with constants, and could not get around the self calling nature of what I am trying to do. I had an errant 'Exit Sub' in the middle of my code that was messing me all up, since it bypassed the decrementing of the counter. Anyhow, thank you for the tip.

Greg
 
Back
Top