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
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.
Dim ctrl As Control
For Each ctrl In Me.Controls
If TypeName(ctrl) = "ToggleButton" Then
ctrl.Value = True 'set button state to pressed
End If
Next ctrl
This sets the state as pressed for every toggle button on the form.
Note that the .Value does not show up in the IntelliSense box because ctrl is of type Control which doesn't have a .Value. If you need IntelliSense then you could workaround like that:
Dim ctrl As Control
For Each ctrl In Me.Controls
If TypeName(ctrl) = "ToggleButton" Then
Dim tggl As ToggleButton
Set tggl = ctrl
tggl.Value = True
End If
Next ctrl
// 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.
Private Sub ToggleButton1_Click()
With Me.ToggleButton1
If .Value = True Then
.BackColor = RGB(255, 0, 0)
Else
.BackColor = -2147483633 'switch to original color
End If
End With
End Sub
Or if you have many buttons, do it more efficiently
'this procedure handles all buttons
Private Sub ToggleButtonClick(ByRef tggl As ToggleButton)
With tggl
If .Value = True Then
.BackColor = RGB(255, 0, 0)
Else
.BackColor = -2147483633 'switch to original color
End If
End With
End Sub
'so you just need to call that function on every _Click event
Private Sub ToggleButton1_Click()
ToggleButtonClick Me.ToggleButton1
End Sub
Private Sub ToggleButton2_Click()
ToggleButtonClick Me.ToggleButton2
End Sub
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 think that the best thing is to work with event and to intercept Press Button
in defining Click() event for all buttons like this
'Form variable to define at begin on code
Dim pbPressed as Control
Dim pbLastPressed as Control
Private Sub pbButton(X)_Click()
'restore previous color only to last pressed
Set pbLastPressed.BackColor = RGB(0,0,155)
Set pbPressed = pbButton(X)
'assign color-pressed to button pressed
pbPressed = RGB(255,0,0)
End sub
where (X) must be replaced by a number as 1 or 2 or 10 !
You can make a fonction, and you obtain
Private Sub pbButton1_Click()
Call ChangeButtonsColor(pbButton1)
End Sub
Private Sub pbButton2_Click()
Call ChangeButtonsColor(pbButton2)
End Sub
Private Sub pbButton3_Click()
Call ChangeButtonsColor(pbButton3)
End Sub
Private Sub ChangeButtonsColor(pb as Button)
'restore previous color only to last pressed
Set pbLastPressed.BackColor = RGB(0,0,155)
Set pbPressed = pb
'assign color-pressed to button pressed
pbPressed = RGB(255,0,0)
End sub
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.
I would suggest to implement a class named TglBtn like that
Option Explicit
Private WithEvents m_ToggleButton As MSForms.ToggleButton
Private Sub m_ToggleButton_Click()
With m_ToggleButton
If .Value Then
.BackColor = RGB(255, 255, 0)
Else
.BackColor = &H8000000F
End If
End With
End Sub
Public Property Set Btn(tb As MSForms.ToggleButton)
Set m_ToggleButton = tb
End Property
In the Userform you can use the following code
Option Explicit
Dim mTgBtns As Collection
Private Sub UserForm_Initialize()
Dim sngControl As MSForms.Control
Dim mTglBtn As tglBtn
Set mTgBtns = New Collection
For Each sngControl In Me.Controls
If TypeName(sngControl) = "ToggleButton" Then
Set mTglBtn = New tglBtn
Set mTglBtn.Btn = sngControl
mTgBtns.Add mTglBtn
End If
Next sngControl
End Sub
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
Public Property Get Caption() As String
Caption = m_ToggleButton.Caption
End Property
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
Private Sub m_ToggleButton_Click()
With m_ToggleButton
If .Value Then
.BackColor = RGB(255, 255, 0)
Else
.BackColor = &H8000000F
End If
End With
MsgBox "You pressed the button with the caption " & Me.Caption
End Sub
Related
I am trying to check all command button in a user form for enabled state and if state is false then enabling it. I have tried this code but runs without error but changes nothing where I manually disable button. It suppose to enable them. Would you please check the code. I get the code from this page
https://stackoverflow.com/questions/49050223/vba-loop-through-buttons-on-userform
Sub form_reset()
Dim ctrl1 As Control
For Each ctrl1 In frmview.Controls
If TypeName(ctrl1) = "commandbutton" Then
Dim cmdbtn As CommandButton
Set cmdbtn = ctrl
If cmdbtn.Enabled = False Then
cmdbtn.Enabled = True
End If
End If
Next
frmview.Show
Try this code
Sub Form_Reset()
Dim ctrl As Control
For Each ctrl In frmview.Controls
If TypeName(ctrl) = "CommandButton" Then ctrl.Enabled = True
Next ctrl
frmview.Show
End Sub
Ok I have figure it out the problem with this code is it only work the button names like btn1, btn2 like. It will not checking the type of control thus making no changes. I was thinking of deleting this post but then think this might save someones time.
Sub form_reset()
Dim ctrl1 As Control
Dim cmdbtn As msforms.CommandButton
For Each ctrl1 In frmview.Controls
If TypeOf ctrl1 Is msforms.CommandButton Then
Set cmdbtn = ctrl1
If cmdbtn.Enabled = False Then
cmdbtn.Enabled = True
End If
End If
Next
frmview.Show
End Sub
Since you can't have a vertical Control Tab in Access, I'm creating a fake one.
I wrote this piece of code to highlight (change fore color to white) the current page:
Private Sub updateBtnColor()
Dim currentPageIndexSZero As Long
Dim ctl As Control
currentPageIndexSZero = Me.tab1
For Each ctl In Me.Controls
If ctl.Tag = "page" & CStr(currentPageIndexSZero) Then
ctl.ForeColor = white
ElseIf InStr(1, ctl.Tag, "page", vbBinaryCompare) Then
ctl.ForeColor = black
End If
Next ctl
End Sub
Every button has got the page it's referring to as a tag, in the form of:
page0
page1
...
pageN
So the loop basically checks the current page, finds the button with the appropriate tag (assuming I named them correctly) and highlights its text.
Now this can be slow since I've got a heavy loaded form or bad practise, so I thought of creating a custom collection instead of looping through the whole Controls Collection.
I wanted to create such structure so I can loop through it, something like:
Enum myButtons
button1 = Forms!myForm!button1
button2 = Forms!myForm!button2
button3 = Forms!myForm!button3
button4 = Forms!myForm!button4
End Enum
And then:
Public Sub updateBtnColor()
Dim curPageZ as Long
Dim button as Control
For Each button in myButtons
With button
If Right$(CStr(.Name, 1)) = curPageZ
.ForeColor = 16777215 ' White
Else ' No need for an additional ElseIf since I already know these are only the wanted buttons
.ForeColor = 0 ' Black
End If
End With
Next button
End Sub
What is the most elegant/fastest/best/proper way to create such structure or, if my idea is not that good, to create such logic?
Thanks!
Cycling thru controls works quite fast, but if you want to speedup this, use Collection for storing objects, not Enum. Collection can be cycled also using For Each....
On form module level create a collection for your buttons:
Dim mcolMyButtons As New Collection
Then fill this collection in Open or Load events. You can use tags:
Dim ctl As Control
For Each ctl In Me.Controls
If TypeOf ctl Is CommandButton Then
If ctl.Tag Like "page*" Then
mcolMyButtons.Add ctl
End If
End If
Next
Or just directly add buttons you want:
mcolMyButtons.Add Me.Button1
mcolMyButtons.Add Me.Button2
mcolMyButtons.Add Me.Button3
mcolMyButtons.Add Me.Button4
Then your sub:
Private Sub updateBtnColor()
Dim ctl As Control
For Each ctl In mcolMyButtons
If ctl.Tag = "page" & Me.tab1 Then
ctl.ForeColor = vbWhite
Else
ctl.ForeColor = vbBlack
End If
Next ctl
End Sub
I have got a piece of code that works which changes a input field from disabled to enabled and changes the colour from gray to white if the corresponsding checkbox is ticked.
Is there a way to loop this or call it for all checkboxes & input fields without having a seperate piece of code for each pair?
The code I have is:
Private Sub CheckBox1_Click()
If CheckBox1.Value = True Then
tb01.Enabled = True
tb01.BackColor = vbWhite
Else: tb01.Enabled = False
tb01.BackColor = vb3DLight
End If
End Sub
Private Sub CheckBox2_Click()
If CheckBox2.Value = True Then
tb02.Enabled = True
tb02.BackColor = vbWhite
Else: tb02.Enabled = False
tb02.BackColor = vb3DLight
End If
End Sub
edit: This code is in a UserForm
Checkboxes are a collection in Excel, you can do something like this:
Sub SelectCheckboxes()
Dim CB As CheckBox
For Each CB In Sheet1
If CB.Name <> Sheet1.CheckBoxes("SkipThisCheckbox").Name Then
CB.Value = 2
End If
Next CB
End Sub
You change the value to all checkboxes, except the "SkipThisCheckbox" checkbox.
Edit: The idea is that the checkboxes are a collection and I have translated your question as "show me how to select/check checkboxes together and not one by one".
On a form it should be something like this:
Private Sub CommandButton1_Click()
Dim cCont As Control
For Each cCont In Me.Controls
If TypeName(cCont) = "Checkbox" Then
Debug.Print cCont
'True or False if checked
'Write your logic here.
End If
Next cCont
End Sub
the more versatile approach is a module class one
here follows a possible application to your case, assuming that TextBoxes and CheckBoxes in your UserForm are paired on a "Name" property basis like "CheckBox1"-"TextBox1", "CheckBox2"-"TextBox2", ...
in the UserForm code pane place the following code
Option Explicit
Dim chkBoxes(1 To 4) As ChkBox_TxtBox_Class 'array of type "ChkBoxClass" which you define in a Class Module
Private Sub UserForm_Initialize()
Dim nControls As Integer, i As Integer
nControls = 4 '<== set here the number of CheckBox-TextBox pairs you have in the Form
For i = 1 To nControls
Set chkBoxes(i) = New ChkBox_TxtBox_Class 'initialize a new instance of 'ChkBoxClass' class and store it in the array i-th position
With chkBoxes(i)
Set .ChkBox = Me.Controls("CheckBox" & i) 'assign the correct CheckBox control to its ChkBox property
Set .TxtBox = Me.Controls("TextBox" & i) 'assign the correct TextBox control to its TxtBox property
.ChkBox.value = False 'set "unchecked" as checkbox initial value
.SetTexBox ' call the class method that will have the "paired" textbox adjust its state accordingly to checkbox value
End With
Next i
End Sub
add a "Class Module" to your project
either clicking Insert-> Class Module in the VBA IDE main Ribbon menu
or right-clicking anywhere in the VBA IDE Project Window and selecting Insert -> Class Module in subsequent sub-menus
expand the "Class Module" node in the Project Window
if you don't see the Project Window you can open it by clicking View-> Project Window in the main ribbon menu, or press "Ctrl+R"
select the new Class you added (it should be some "Class1" or the likes) and change its name to "ChkBox_TxtBox_Class" in the Property Window "Name" textbox
if you don't see the Property Window you can open it by clicking View-> Property Window in the main ribbon menu or press "F4"
in the Class Module code pane place the following
Option Explicit
'declare class properties of CheckBox and TextBox type to be "paired" in every instance of this class. the CheckBox one will be associated to events
Public WithEvents ChkBox As MSForms.CheckBox ' ChkBox is a property of the class of type CheckBox. it's associated to events
Public TxtBox As MSForms.TextBox ' TxtBox is a property of the class of type TextBox
' events associated to ChkBox class property
Sub ChkBox_Change()
Call SetTexBox 'call the "method" (i.e. a Sub attached to the class) associated to ChkBox property state change
End Sub
Sub SetTexBox()
'sub that sets the state of the associated TextBox accordingly to the state of the associated CheckBox
With Me.ChkBox
If .value Then
TxtBox.Enabled = True
TxtBox.BackColor = vbWhite
Else
TxtBox.Enabled = False
TxtBox.BackColor = vb3DLight
End If
End With
End Sub
run your routine
I have a userform which is dynamically filled by checkboxes. To improve usability I've added a checkbox "Select all" which either selects or deselects all checkboxes. This works perfectly. Now I want the "Select all" checkbox to be unchecked (value=False) automatically once one of the other checkboxes is unchecked.
In order to achieve this I've created a class module. This class module also does what it's supposed to. But, and here's my problem, once the value of "Select all" is changed, the "Select all" checkbox_click event is triggered, which means all other checkboxes are being unchecked as well, and that's obviously not what I want! I've already tried to use the MouseDown and MouseUp events instead, but these events behave irregular and often lead to the wrong results.
Question: How do I stop the Click event from running everytime the value of this checkbox is changed without the checkbox actually being clicked?
Here's my code:
Private colTickBoxes As Collection
Private Sub UserForm_Initialize()
Dim ChkBoxes As cls_RIRI
Dim ctrl As Control
'Controls are created on run time here
'Some events to change the height of the userform and the top value of several buttons
'Make sure click events work
Set colTickBoxes = New Collection
For Each ctrl In Me.Controls
If TypeName(ctrl) = "CheckBox" And Left(ctrl.Name, 1) = "M" Then
Set ChkBoxes = New cls_RIRI
ChkBoxes.AssignClicks ctrl
colTickBoxes.Add ChkBoxes
End If
Next ctrl
Set ctrlCHK = Nothing
Set ChkBoxes = Nothing
Set ctrl = Nothing
End Sub
And the class module:
Private WithEvents chkBox As MSForms.CheckBox
Public Sub AssignClicks(ctrl As Control)
Set chkBox = ctrl
End Sub
Private Sub chkBox_Click()
If chkBox.value = False Then UserForms(0).Controls("chkSelAll").value = False
End Sub
And the chkSelAll_Click sub:
Private Sub chkSelAll_Click()
Dim ctrl As Control
For Each ctrl In Me.Controls
If TypeName(ctrl) = "CheckBox" And Left(ctrl.Name, 1) = "M" Then
If chkSelAll.value = True Then
ctrl.value = True
Else
ctrl.value = False
End If
End If
Next
Set ctrl = Nothing
End Sub
Add a public variable, say blnBypassNonUIClick and set this, then when coming from the UI, by a human click set it to false, and when setting the select all the same. Your select all, shouldnt activate click if you're setting the .value by code. Something like this....
Public blnNonUI As Boolean
Private Sub CheckBox1_Click()
If Not blnNonUI Then
MsgBox "hello"
End If
End Sub
Private Sub UserForm_Click()
blnNonUI = True
Me.CheckBox1.Value = 1
blnNonUI = False
End Sub
Nathan_Sav gave me this idea and it works:
Public blnHumanClick As Boolean
Private Sub chkSelAll_Click()
If blnHumanClick = True Then
Dim ctrl As Control
For Each ctrl In Me.Controls
If TypeName(ctrl) = "CheckBox" And Left(ctrl.Name, 1) = "M" Then
If chkSelAll.value = True Then
ctrl.value = True
Else
ctrl.value = False
End If
End If
Next
Set ctrl = Nothing
blnHumanClick = False
End If
End Sub
Private Sub chkSelAll_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
blnHumanClick = True
End Sub
I have a userform with a multiple frames, all filled with multiple checkboxes. I've named the checkboxes to their corresponding Excel cells. Now I want to make VBA run on clicking any of these checkboxes on run time. I know I can do this by creating a click-sub for every individual checkbox, but there must be a cleaner way to do this.
So far I've tried to put this code in the userform_Click and userform_Mousedown events, but they don't run when I click the checkboxes. Does anyone have an idea how to do this?
Dim iControl As Control
For Each iControl In Me.Controls
If TypeName(iControl) = "CheckBox" Then
If iControl.Value = True And Range(iControl.Name).Value = "" Then
Range(iControl.Name).Value = Format(Now, "dd.mm.yyyy")
ElseIf iControl.Value = True And Range(iControl.Name).Font.Color = vbWhite Then
Range(iControl.Name).Font.Color = vbBlack
ElseIf iControl.Value = False And Range(iControl.Name).Value <> "" Then
Range(iControl.Name).Font.Color = vbWhite
End If
End If
Next
As SilentRevolution said - you need an event to fire when you click the button. You're just after a single procedure to fire all check box click events.
So:
Create a class module called cls_ChkBox.
In the class module you'll add the Click event code:
Option Explicit
Private WithEvents chkBox As MSForms.CheckBox
Public Sub AssignClicks(ctrl As Control)
Set chkBox = ctrl
End Sub
Private Sub chkBox_Click()
ThisWorkbook.Worksheets("Sheet1").Range(chkBox.Name).Value = Format(Now, "dd.mm.yyyy")
End Sub
Now you just need to attach the chkBox_Click event to each check box on your form. In your user form add this code:
Option Explicit
Private colTickBoxes As Collection
Private Sub UserForm_Initialize()
Dim ChkBoxes As cls_ChkBox
Dim ctrl As Control
Set colTickBoxes = New Collection
For Each ctrl In Me.Controls
If TypeName(ctrl) = "CheckBox" Then
Set ChkBoxes = New cls_ChkBox
ChkBoxes.AssignClicks ctrl
colTickBoxes.Add ChkBoxes
End If
Next ctrl
End Sub
Each check box is given its own instance of the class, which is stored in the colTickBoxes collection.
Open the form and the cell in Sheet1 will update to show the date depending on the name of the check box.
You need an event to run code, if there is no event, the macro cannot start. I don't know if there is a single event that triggers for any button or checkbox that is clicked.
If the code you want to execute is the same every time except the control, you could write a private sub in the userform module which is called for each event, the private sub can take an input between the () for example.
Private Sub CheckBox1_Click()
Call ExecuteCode(Me.CheckBox1)
End Sub
Private Sub CheckBox2_Click()
Call ExecuteCode(Me.CheckBox2)
End Sub
Private Sub CheckBox3_Click()
Call ExecuteCode(Me.CheckBox2)
End Sub
Private Sub ExecuteCode(IControl As Control)
If TypeName(IControl) = "CheckBox" Then
If IControl.Value = True And Range(IControl.Name).Value = "" Then
Range(IControl.Name).Value = Format(Now, "dd.mm.yyyy")
ElseIf IControl.Value = True And Range(IControl.Name).Font.Color = vbWhite Then
Range(IControl.Name).Font.Color = vbBlack
ElseIf IControl.Value = False And Range(IControl.Name).Value <> "" Then
Range(IControl.Name).Font.Color = vbWhite
End If
End If
End Sub
I just learned this today and thought it might help? Most of the questions, and responses for that matter, to questions regarding checkboxes, listboxes, etc. seem to not distinguish between those forms are inserted directly on the worksheet or are imbedded in a UserForm.
This may work for a checkbox - it works for a ListBox on a UserForm. If you want code to run after a selection, the code you must write has to be in module of the UserForm. I had no clue how to access. Once you have inserted a UserForm in your VBE, add the ListBoxes or whatever to the UserForm. Right click on the UserForm in the upper left project window and select "view code." Here is where you'll place the code, in my case a "change event" such that after a selection is made from the ListBox, other code is automatically run. Her for example:
Sub lstBoxDates_Change()
Dim inputString1 As String
inputString1 = Format(UserForm1.lstBoxDates.Value, "mm-dd-yyyy")
Call EnterDates(inputString1)
Unload Me
End Sub
To explain: Again this code is in the UserForm Module. I named my ListBox,
lstBoxDates. In my main code that I call - EnterDates, I use the variable name = inputString1. The value or date that I have selected from the ListBox is captured from the UserForm1 by UserForm1.lstBoxDates.Value - and I format that to a date, otherwise you see just a number. This is for only one selection.
Because I Dim here, no need to Dim in your main code. The sub for the main code
needs to accept the variable you are passing to it:
Sub EnterDates(inputString1)
This is very generalized but maybe something will click so you can get what you are after. I hope so, for I've worked on this a full two days!!