The CheckBox control allows users to select one or more options from a set of choices. In Excel VBA, CheckBoxes are commonly used in UserForms to create interactive interfaces for your applications.
CheckBoxes are ideal for:
This example demonstrates how to use CheckBox controls to display different sales data. The user can choose to view sales for individual fruits or the total sales.
Private Sub CommandButton1_Click()
' Check which CheckBox is selected and display appropriate message
If CheckBox1.Value = True And CheckBox2.Value = False Then
MsgBox "Quantity of apples sold is " & Cells(2, 2).Value
ElseIf CheckBox2.Value = True And CheckBox1.Value = False Then
MsgBox "Quantity of oranges sold is " & Cells(2, 3).Value
Else
MsgBox "Total quantity of fruits sold is " & Cells(2, 4).Value
End If
End Sub
When dealing with multiple CheckBoxes, you can use a Select Case statement for cleaner code:
Private Sub ProcessSelections()
Dim message As String
Select Case True
Case CheckBox1.Value And Not CheckBox2.Value
message = "Apple sales: " & Cells(2, 2).Value
Case CheckBox2.Value And Not CheckBox1.Value
message = "Orange sales: " & Cells(2, 3).Value
Case CheckBox1.Value And CheckBox2.Value
message = "Combined sales: " & Cells(2, 4).Value
Case Else
message = "Please select at least one option"
End Select
MsgBox message
End Sub
Option Buttons (also called radio buttons) allow users to select exactly one option from a set of mutually exclusive choices. Unlike CheckBoxes where multiple options can be selected, Option Buttons automatically deselect all others in their group when one is selected.
This example shows how to determine which OptionButton the user selected in a simple survey form.
Private Sub CommandButton1_Click()
' Determine which OptionButton is selected
If OptionButton1.Value = True Then
MsgBox "Option 1 is selected - Thank you for your feedback!"
ElseIf OptionButton2.Value = True Then
MsgBox "Option 2 is selected - We appreciate your input."
Else
MsgBox "Option 3 is selected - Your opinion matters to us."
End If
End Sub
You can create OptionButton groups dynamically at runtime:
Private Sub CreateOptionGroup()
Dim i As Integer
Dim optBtn As MSForms.OptionButton
' Create a group of 5 OptionButtons
For i = 1 To 5
Set optBtn = UserForm1.Controls.Add("Forms.OptionButton.1", "optChoice" & i)
With optBtn
.Caption = "Choice " & i
.Left = 20
.Top = 20 + (i * 25)
.Width = 100
.GroupName = "SurveyChoices"
End With
Next i
End Sub
| Feature | CheckBox | OptionButton |
|---|---|---|
| Selection | Multiple items can be selected | Only one item can be selected |
| Value | Independent True/False for each | Only one in group can be True |
| Best Use | Options that aren't mutually exclusive | Mutually exclusive choices |
Copyright ® 2020 Dr.Liew Voon Kiong . All rights reserved [Privacy Policy]
Contact: Facebook Page