In VBA, you can create a CheckBox where a user can check or uncheck the option. A Checkbox is often used in Userforms, but can also be used in a Worksheet. In this tutorial, you will learn how to create a Checkbox, 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:
Image 1. Insert a Checkbox in the Worksheet
When you select the Checkbox which you inserted, you can click on Properties under the Developer tab:
Image 2. Change Checkbox Properties
Here you can set different properties of the Checkbox. For the beginning, we changed the attribute Name to cmbCheckbox. Now, 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 users choice (checkbox checked or not). In order to retrieve a value that is selected by user, you need to use this code:
If Sheet1.chbCheckBox.Value = True Then
Sheet1.Range("C3") = "Agree"
Sheet1.Range("C3") = "Don't agree"
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.chbCheckbox. The value of the checkbox can be true or false.
Image 3. Get a selected value from the Checkbox in VBA
As we checked the checkbox, the value of Sheet1.chbCheckbox.Value is true, so the result in C3 is Agree.
Use a Checkbox in a Userform
As we mentioned, Checkbox is most often used in Userforms. To explain how you can do it, we will first insert an Userform. In VBA editor, right-click on Module name, click on Insert and choose UserForm:
Image 8. Insert a 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:
Image 9. Insert a Checkbox 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.
Image 10. The Checkbox in the Userform
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.