VBA Worksheet change event bypass?

笑着哭i 提交于 2019-11-28 10:52:12

I think you want the EnableEvents property of the Application object. When you set EnableEvents to False, then nothing your code does will trigger any events and none of the other event code will run. If, for example, your code changes a cell it would normally trigger the Change event or the SheetChange event. However, if you structure it like this

Application.EnableEvents = False
    Sheet1.Range("A1").Value = "new"
Application.EnableEvents = True

then changing A1 won't trigger any events.

Sometimes it's beneficial to have to have your code trigger event code and sometimes it's not. Use EnableEvents when you want to prevent it.

This is an important modification to the answer from @Dick Kusleika.

When turning off the EnableEvents setting, it's a good idea to include error handling to turn EnableEvents back on. If you don't and the script throws an error, the change event trigger (your script) will stop working until you manually turn EnableEvents back on.

Ideally, you would place the following line immediately before any code that re-triggered your change event. The first line tells VBA to goto a label called "enableEventsOn" when it encounters an error. The second line bypasses change events.

On Error Goto enableEventsOn:
Application.EnableEvents = False

Then place this code immediately after code that re-triggered your change event. This turns change event triggers back on and returns normal error handling to your script.

Application.EnableEvents = True
On Error Goto 0

Finally, place this code at the end of your script. It's a label referred to above. If an error is encountered between "On Error Goto enableEventsOn:" and "On Error Goto 0" then the script will go here and turn EnableEvents back on, leaving it ready to start the script the next time you change your worksheet.

enableEventsOn:
Application.EnableEvents = True

Too risky in my own opinion.

I'd use a variable, named "skip_update" that is set to "True" in the beginning of each macro and to false when it ends.

e.g :

dim skip_update as Boolean = False

sub auto_macro_when_modify()
   if skip_update == True then
      exit sub ' NO CHANGE !
   end if
end sub

sub other_macro
    skip_update = True
    ' ( do stuff)
    skip_update = False
end sub

You can hold down the CTRL key while doing an entry that would trigger the change on event routine. I have a routine to sum the values in a selected range in a given column. If I drag cursor from rows 1 to 5, highlighting them, then the sum of these is saved to the clipboard. Any entry in a cell in this column triggers the routine. If I hold down the CTRL key while doing the intended action or any entry in a cell in the column the routine is not initiated. May not work for more complicated ChangeEvent scenarios.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!