In this Article
In VBA, you can create a CheckBox where a user can check or uncheck the option. Checkboxes are often used in UserForms, but can also be used in a Worksheet. In this tutorial, you will learn how to create a Checkbox (in both VBA and in Excel Worksheets), get a user choice in VBA and use it in code.
If you want to learn how to create a Listbox, click here: VBA Listbox
If you want to learn how to create a Combobox, click here: VBA Combobox
Create a Checkbox
In order to insert a Checkbox in the Worksheet, you need to go to the Developer tab, click Insert and under ActiveX Controls choose Check Box:
When you select the Checkbox which you inserted, you can click on Properties under the Developer tab:
Here you can set different properties of the Checkbox. First, we changed the attribute Name to cmbCheckbox. Next, we can use the Checkbox with this name in VBA code.
Also, we changed the text which appears next to the checkbox to Agree with Terms. To do this, you need to set the attribute Caption.
Get a Selected Item of a Checkbox in VBA
The purpose of a Checkbox is to get a user’s choice (checkbox checked or not). In order to retrieve a value that is selected by user, you need to use this code:
If Sheet1.cmbCheckBox.Value = True Then Sheet1.Range("C3") = "Agree" Else Sheet1.Range("C3") = "Don't agree" End If
We want to populate the cell C3 with Agree if the checkbox is checked and Don’t agree otherwise. The value of the checkbox is in the Value attribute of the object Sheet1.cmbCheckbox. The value of the checkbox can be true or false.
As we checked the checkbox, the value of Sheet1.cmbCheckbox.Value is true, so the result in C3 is Agree.
Use a Checkbox in a UserForm
As we mentioned, Checkboxes are most often used in UserForms. To explain how you can do it, we will first insert an Userform. In the VBA Editor, right-click on Module name, click on Insert and choose UserForm:
To display controls for inserting, you need to enable the Toolbox. To do this, click on the Toolbox icon in the toolbar. After that, you will get the windows with all the controls available. You can click on Checkbox to create it in the Userform:
In the properties window, we will change the name of the Checkbox to chbCheckBox and caption to Agree with Terms. When we run the Userform, we get the Checkbox in it.
If you want to get selected value from the Checkbox, you need to use the same logic for the Checkbox in a Worksheet, which is explained earlier in the article.
VBA Coding Made EasyStop searching for VBA code online. Learn more about AutoMacro - A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!