I have not used VBA so quite new - but all searches have not given me the answer
its a simple question really. I have a group of buttons in an Excel Form. The code is very similar when each one is pressed, and for each pressed button, I would like the colour of the button to change. So in reality, I have something like this for each button
UserForm2.CommandButton17.BackColor = RGB(255,255,0)
I would like to go through each button. Check if it is pressed, and then set the colour accordingly.
I actually want to say something like
for counter in 1 to 100
if (ispressed((CommandButton & counter )) then
I have found the following construct:
Dim ctrl as Control
For Each ctrl in UserForm1.Controls
ctrl.BackColor = RGB(255,0,0)
end for
this construct works - but I cant figure out how to check if the button is pressed.
Some of the answers show the above construct, with ctrl.Value = True
but those are for checkboxes and radio buttons. I don't even get the ctrl.Value
option with buttons, so I can't use it anyway
Every example of code I have found glosses over this requirement.
Can someone help
I think that the best thing is to work with event and to intercept Press Button in defining Click() event for all buttons like this
where (X) must be replaced by a number as 1 or 2 or 10 !
You can make a fonction, and you obtain
Don't forget to add other event as KeyPress() that can make same action than clicking the Button.
If you have more than 10 buttons, you can perhaps create the buttons dynamically.
Use a ToggleButton instead of a CommandButton if you want it to represent a state.
To initialize a state for each toggle button you can loop through the control.
This sets the state as pressed for every toggle button on the form.
// Edit
Everytime a toggle button gets clicked it triggers a
_Click
event for that button. So you will need such an event for each button.Or if you have many buttons, do it more efficiently
But you still need a
_Click()
event for every button to call that procedure.You can also evaluate the
.Value
state of each button in the_Click()
event to set/unset your asterisk.I would suggest to implement a class named TglBtn like that
In the Userform you can use the following code
When you click on one of togglebuttons on your userform the class will take care of the background color.
EDIT If you want to access the caption of the Togglebutton you could add the following property to the class
EDIT2 Just as an example of using the property, you could change the Click event as below and everytime you click a MsgBox with the caption of the button will appear