(Excel Userform) Check if all checkboxes in a Userform are checked - vba

Never tried UserForm checkboxes before so I don't even know how to point to the Checkboxes in a Userform.
This is what I have at the moment....and I know, I know, it is completely wrong. Please help?
Private Sub Step1_Confirm_Click()
Dim i As Byte
Dim Done As Boolean
For i = 1 To 4
If Step1_(i).value = True Then
Done = True
End If
Next i
If Not Done = True Then
MsgBox "Please make sure you have done all"
End If
End Sub
Basically I have:
A Userform called IOSP_Acc_R_Approval_Step1
4 checkboxes called Step1_1; Step1_2; Step1_3; Step1_4
A button called Step1_Confirm
I want the button to show Error, if not all checkboxes are checked - meaning that all checkboxes have to be checked....(in case my English is too bad to convey my meaning)

Try the code below (explanations inside the code as comments):
Private Sub Step1_Confirm_Click()
Dim i As Long
Dim Ctrl As Control
' loop through all user_form control
For Each Ctrl In IOSP_Acc_R_Approval.Controls
If TypeName(Ctrl) = "CheckBox" Then ' check if control type is Check-Box
If Ctrl.Value = True Then ' check if check-box is checked
i = i + 1
End If
End If
Next Ctrl
If i < 4 Then ' not all 4 check-boxes are checked
MsgBox "Please make sure you have done all"
End If
End Sub

You can do this by:
assume that all checkboxes are checked by setting a flag to True
iterate the checkboxes and if one is not checked set the flag to False and exit
at the end of the loop, if all checkboxes were checked then the flag is still True
You can refer to the checkboxes dynamically by using the Me.Controls collection and pass in the name of the checkbox like "Step1_" & i.
Example code:
Option Explicit
Private Sub Step1_Confirm_Click()
Dim i As Long '<-- use Long, not Byte
Dim blnResult As Boolean
' set a flag to assume that it is true that all checkboxes are checked
blnResult = True
' get the value of each check box
For i = 1 To 4
If Me.Controls("Step1_" & i).Value = False Then
blnResult = False
Exit For '<-- skip loop if at least one box not checked
End If
Next i
' check the value of the flag
If blnResult = False Then
MsgBox "Please make sure you have done all"
Else
' all boxes checked ...
MsgBox "All checked"
End If
End Sub

Done=true
For i = 1 To 4
Done = Done*Step1_(i).value
Next i
if done `then`
msgbox "All checkboxes are checked"
end if

Related

VBA "All" checkbox with listbox deselect loop issues

I have a check box that is used for "ALL" (selected by default) selections in a muliselect listbox that is deselected when an item in the listbox is selected. I also coded it so when "ALL" is selected, then it clears the listbox selections and checks the box. It ends up looping through the different subs and makes it annoying for the user.
For instance, when I click an item in the listbox it selects that value, then deselects the checkbox. Since the checkbox is deselected, it goes back through the listbox and deselects the selected item. It loops between the two subs a couple times and ends up only working correctly half the time.
Can I prevent entering the other sub?
Is there better logic so it won't loop as it does?
or maybe an better method to achieve this?
Multiselect listbox:
Private Sub Mkts_Change()
If Me.cheMkts.Value = True Then
Me.cheMkts.Value = False
End If
End Sub
Checkbox:
Private Sub cheMkts_Click()
Dim i As Integer
For i = 0 To Mkts.ListCount - 1
If Me.Mkts.Selected(i) = True Then
Me.Mkts.Selected(i) = False
End If
Next
End Sub
What about adding an If statement around your cheMtks_Click()?
This way when your code deselects it automatically it shouldn't trigger the loop.
Private Sub cheMkts_Click()
If Me.cheMkts.Value = True Then
Dim i As Integer
For i = 0 To Mkts.ListCount - 1
If Me.Mkts.Selected(i) = True Then
Me.Mkts.Selected(i) = False
End If
Next
End If
End Sub
Thanks for your help, Ruben. That corrects the error on the one end, but I am still having issues on the other side. When I have a selection and click the "ALL" box it deselects the check.
I came up with this code, which works beautifully in combo to your suggestion, but only when I have one item selected. If there is anything more, then it still goofs up. Figured I would post to see if you or someone else could advise a solution for multiple selections.
Private Sub Mkts_Change()
Dim i As Integer, count As Integer
For i = 0 To Mkts.ListCount - 1
If Me.Mkts.Selected(i) = False Then
count = count + 1
End If
Next
If Me.cheMkts.Value = True And count <> Mkts.ListCount Then
Me.cheMkts.Value = False
End If
End Sub

Reference checkbox name/value in a subroutine

Is there a way to pass a checkbox value from a userform? I've seen it done when the checkbox is on the worksheet but I haven't been able to get it to work when it comes from my userform.
I have several repeating if statements and the only difference between them is the name of the checkbox. I'm sure there's a simple fix that I just haven't found yet. Any help is appreciated.
Edit: included code
If LockboxCheckBox.Value = True Then
If IsEmpty(wsInput.Cells(emptyRow, productCol)) Then
wsInput.Cells(emptyRow, productCol).Value = LockboxCheckBox.Caption
Else: wsInput.Cells(emptyRow, productCol).Value = wsInput.Cells(emptyRow, productCol).Value & ", " & LockboxCheckBox.Caption
End If
End If
I want to make this a small subroutine and need to pass the checkbox.value as well as the checkbox.caption to it when I call it.
The following code example demonstrates how to pass a Checkbox control on a UserForm to another procedure, get the checkbox's value and caption, and do something with them.
Note that I choose to pass the checkbox, rather than the value and caption as two parameters, as this will reduce the amount of code you need to type.
Private Sub btnOK_Click()
Dim chk As MSForms.CheckBox
Set chk = Me.CheckBox1
ProcessCheckBox chk
ProcessCheckBox Me.CheckBox2
End Sub
Sub ProcessCheckBox(chk As MSForms.CheckBox)
Dim chkVal As Boolean
Dim chkCap As String
chkVal = chk.value
chkCap = chk.Caption
If chkVal = True Then
Debug.Print chkCap & " is true"
Else
Debug.Print chkCap & " is false"
End If
End Sub

vba - Msg if box if checked - but not if unchecked

I am trying to write code for a message to pop up if a checkbox is checked. My spreadsheet has a LOT of checkboxes, and I only want it to do this for the checkboxes in column H. I believe the best way may be to assign a macro to all checkboxes using vba using something like the following code (Except this is not working):
ActiveSheet.Shapes.Range(Array("h9:h89")).Select
Selection.OnAction = "Sheet4.Checkbox"
The second problem I have is that I only want the message to pop-up when it is checked, not when it is unchecked. The following works when the macro is assigned mannually, but for both checking and unchecking. The commented out sections are examples of some of the things I have tried. I believe they are ActiveX checkboxes.
Sub Checkbox()
' Dim rangeVar As Range
'
' rangeVar = ("h9:h89")
'
'With rangeVar
' If WorksheetFunction.Or(.Cells) = True Then
MsgBox ("Are you sure you want to check this box?")
Exit Sub
' End If
'End With
' Dim chk As Checkbox
'
' For Each chk In rangeVar
' If chk.Value = True Then
' MsgBox ("Are you sure you want to check this box?")
' Exit Sub
' End If
' Next chk
End Sub
Thank you!
Assigning the action:
Sub AssignClicks()
Dim cb
For Each cb In ActiveSheet.CheckBoxes
If Not Application.Intersect(cb.TopLeftCell, _
ActiveSheet.Range("H:H")) Is Nothing Then
cb.OnAction = "Sheet1.ClickedIt"
End If
Next cb
End Sub
In the sheet code module:
Sub ClickedIt()
Dim cb As CheckBox
Set cb = Me.CheckBoxes(Application.Caller)
If cb.Value = 1 Then
MsgBox "checkbox at " & cb.TopLeftCell.Address() & " is checked"
End If
End Sub
...or you can assign the action to all of your checkboxes and use code in ClickedIt to determine whether the current checkbox is in Col H.

Excel - Returning the caption of the selected option button

Probably a silly question with a simple answer but I am a real novice when it comes to userforms.
I have "Frame 3" with 5 different option buttons (Dest1, Dest2, Dest3, Dest4, Dest5) After an option is selected, where is the caption value of the selected option stored? How can I access that with vba.
Thank you,
Josh
Here's just some example code you can use. Add your Option Buttons to groups, and then you can go from there. I used groups since you had multiple frames, and you can check based on group, and have multiple groups, and check which one's selected for each group.
Private Sub CommandButton1_Click()
Dim x As Control
' Loop through ALL the controls on the UserForm.
For Each x In Me.Controls
' Check to see if "Option" is in the Name of each control.
If InStr(x.Name, "Option") Then
' Check Group name.
If x.GroupName = "Grp1" Then
' Check the status of the OptionButton.
If x.Value = True Then
MsgBox x.Caption
Exit For
End If
End If
End If
Next
End Sub
You can also access the option buttons through the frame-ojbect that holds them (if you have other frames and controls you don't want to go through):
Option Explicit
Sub Test()
Dim oCtrl As Control
'***** Try only controls in Frame3
For Each oCtrl In Frame3.Controls
'***** Try only option buttons
If TypeName(oCtrl) = "OptionButton" Then
'***** Which one is checked?
If oCtrl.Value = True Then
'***** What's the caption?
Debug.Print "You have checked option " & oCtrl.Caption
Exit For
End If
End If
Next
End Sub
The Label Text associated with an Option Button is obtainable by using OptionButton1.Caption
If you are using a loop, just substitute the OptionButton1 with your variable for option buttons and it will pull through the one you need when conditions are met. eg:
For xitem = 1 To 5
xFrm = "OptionButton" & xitem
For Each fItem In Me.Controls
If fItem.Name Like xFrm Then
If fItem.Value Then
k = fitem.Caption
End If
End If
Next fItem
Next xitem
In my case, I wanted the caption of the toggle that was selected in an option group to be passed on to a subform filter. e.g. choosing toggle "black" filters subform to all cars where strColour = "black".
I ended up with this:
Private Sub OptionGroupName_Click()
Dim Caption As String
Caption = OptionGroupName.Controls.Item(OptionGroupName.Value - 1).Caption
Me.SubformName.Form.Filter = "[SubformField] = """ & Caption & """"
Me.SubformName.Form.FilterOn = True
End Sub
Not to dog pile on everyone else's options but I created a function that takes the radio group name and spits out the selected radios coresponding label caption. Was using it in Access not Excel.
Only works provided you name your controls similarly....
i.e. (lblRadioButton1 & optRadioButton1)
Function GetSelectedRadioButtonCaption(ByVal optionGroupName As OptionGroup) As String
Dim oCtrl As Control
Dim oCtrl2 As Control
Dim optionLabelName As String
Dim optionLabelObject As Label
Dim optionButtonObject As OptionButton
For Each oCtrl In optionGroupName.Controls
'***** Try only option buttons
If TypeOf oCtrl Is OptionButton Then
'***** Which one is checked?
Set optionButtonObject = oCtrl
If optionButtonObject.OptionValue = optionGroupName.Value Then
'***** What's the caption?
optionLabelName = Replace(oCtrl.Name, "opt", "lbl")
For Each oCtrl2 In optionGroupName.Controls
If oCtrl2.Name = optionLabelName Then
Set optionLabelObject = oCtrl2
GetSelectedRadioButtonCaption = optionLabelObject.caption
Exit For
End If
Next
End If
If GetSelectedRadioButtonCaption <> "" Then
Exit For
End If
End If
Next
Exit_GetSelectedRadioButtonCaption:
End Function

How can I check whether the data already exists in combobox list?

How can I check if the data from cmbTypeYacht.text already exists in cmbTypeYacht.list?
Here's what I've got:
Dim TypeYacht As String 'Type of yacht input
TypeYacht = cmbTypeYacht.Text
If TypeYacht = ("cmbTypeYacht list") Then
MsgBox "Type of Yacht is already on the list", vbExclamation, "Yacht Chantering"
Else
cmbTypeYacht.AddItem cmbTypeYacht.Text
With cmbTypeYacht
.Text = ""
.SetFocus
End With
End If
sorry about the tag im not quite sure which is it but im using Microsoft Visual Basic app.
The ComboBox class has a FindStringExact() method that will do the trick for you, like this:
Dim resultIndex As Integer = -1
resultIndex = cmbTypeYacht.FindStringExact(cmbTypeYacht.Text)
If resultIndex > -1 Then
' Found text, do something here
MessageBox.Show("Found It")
Else
' Did not find text, do something here
MessageBox.Show("Did Not Find It")
End If
You can also just loop through the list as well, like this:
Dim i As Integer = 0
For i = 0 To cmbTypeYacht.Items.Count - 1
If cmbTypeYacht.Items.Contains(cmbTypeYacht.Text) Then
MessageBox.Show("Found It")
Exit For
End If
Next
I'm working in Excel 2013 and there is no FindStringExact or .Items.Contains so, neither of those are valid. There is also no need to iterate the list. It is very simple actually. Given a userform "MyUserForm" and a combobox "MyComboBox",
If MyUserForm.MyComboBox.ListIndex >= 0 Then
MsgBox "Item is in the list"
Else
MsgBox "Item is NOT in the list"
End If
Explanation: If selected item is not in the list, .ListIndex returns -1.
The combobox in vba has a property called MatchFound. It will return true if the value you inputted in the combobox (ComboBox.Value) existed before.
Put below code in the update event of the combobox for trial
Private Sub ComboBox_AfterUpdate()
If ComboBox.MatchFound = True then
Msgbox "Value exist"
End If
End Sub
Check it out:
https://msdn.microsoft.com/en-us/vba/outlook-vba/articles/combobox-matchfound-property-outlook-forms-script
You do not need to iterate through combobox.items. Items.Contains will already iterate through the list for you.
Simply use:
If cmbTypeYacht.Items.Contains(cmbTypeYacht.Text) Then
MessageBox.Show("Found It")
Exit For
End If
Searching: VBA check whether the data already exists in combobox list?
but vba doesnt have the properties above.
Sub TestString()
Dim myString As String
Dim i As Long
Dim strFound As Boolean
'Just for test purposes
myString = "Apple"
strFound = False
With Me.ComboBox1
'Loop through combobox
For i = 0 To .ListCount - 1
If .List(i) = myString Then
strFound = True
Exit For
End If
Next i
'Check if we should add item
If Not strFound Then .AddItem (myString)
End With
End Sub
This was found after a lot of searching at http://www.ozgrid.com/forum/showthread.php?t=187763
and actually works