excel vba - execute macro when cell value changes due to another macro -
i have sheet 2 buttons. 1 button places value in cell (e2) , other button counts value (in e2) down 1 every time pushed. want value in e2 cell dictate color of d2, such d2 red whenever value of cell > 0 , green when =< 0.
here 2 buttons:
button 1
sub use2() range("e2").value = range("d2") end sub
button 2
sub subtract1() range("e2").value = range("e2").value - 1 end sub
i added code:
private sub worksheet_change(byval target range) if target.address = range("e2").address , target.value >0 range("d2").interior.color = vbred end if end sub
i didn't green part because works if manually enter value greater 0 in e2. doesn't work if value of e2 changes value > 0 pushing button 1. can me change works. thanks!
whenever usingworksheet_change
event
1) use application.enableevents
prevent events firing when other code running.
2) use error handling enableevents set true
private sub worksheet_change(byval target range) application.enableevents = false on error resume next if not intersect(range("e2"), target) nothing if target.value > 0 range("d2").interior.color = vbred else range("d2").interior.color = vbgreen end if end if application.enableevents = true end sub
it can achieved using conditional formatting.
Comments
Post a Comment