VBA Controls – A Guide for Everyone

VBA Controls

“I want to think that there is someone with sound judgement at the controls” – Martin Feldstein

 
 

Introduction

In the first post on UserForms we looked at the general use of the UserForm.

In this post we are going to look at the individual VBA controls and how to use them. We will cover the most commonly used VBA controls. These are the Checkbox, ComboBox, CommandButton, Label, ListBox and TextBox. For each control, I will cover their most common uses and provide plenty of code examples you can use in your own projects.

 
 

The Controls

We add controls to the UserForms to allow the user to make selections, enter text or click a button. To add a control to a UserForm we do the following

  1. Go to the Toolbox dialog – if not visible select View->Toolbox.
  2. Click on the control icon you want to add – the icon will appear selected(pressed in) until you click another one.
  3. Put the cursor over the UserForm.
  4. Hold down the left mouse button and drag until the control is the size you want.
  5. To select or move a control click on the Select Objects icon(very left one) on the toolbox and this will put you in select mode.

 
 
The following table shows a list of the common controls

ControlDescription
CheckBoxTurn item on/off
ComboBoxAllows selection from a list of items
CommandButtonClick to perform action
Label Displays text
ListBoxAllows selection from a list of items
TextboxAllows text entry

 
 

Properties of the Controls

The screenshot below shows the three important Windows when adding controls to a UserForm. These are

  1. The Properties Window.
  2. The Toolbox Dialog.
  3. The UserForm design Window.

 
 

VBA UserForm

UserForm Windows

 
 
If you click on any control or the UserForm itself you will see the properties of the selected item displayed in the Properties window. You can change the name, caption etc. in this Window.

To change the name of the UserForm do the following

  1. Click on the UserForm in the Project window or click on the UserForm itself.
  2. Click in the (Name) field of the Properties window.
  3. Enter the new name in this field.

 
 

Adding the Code

You can view the code of the UserForm in the following ways
 

  1. Double click on the UserForm.
  2. Right click on the UserForm itself and select View Code.
  3. Right click on the UserForm in the Project windows and select View Code.

 
 

Common control functions

The following table shows the most commonly used functions that are available to all controls.

FunctionOperationExample
EnabledEnable/Disable controlcombobox.Enabled = True
textbox.Enabled = False
SetFocusSets the focus to the control
(cannot use with the Label)
combobox.SetFocus
VisibleShow/Hide controlcombobox.Visible = True
textbox.Visible = False

 
 

Private Sub checkboxAddNotes_Click()

    ' Enable texbox when checkbox set to true
    If checkboxAddNotes.Value = True Then
        textboxNotes.Enabled = True
        textboxNotes.SetFocus
    Else
        textboxNotes.Enabled = False
    End If
         
End Sub	 

 
 

The CheckBox

 
 

The CheckBox Cheat Sheet

FunctionOperationExample
CaptionGet/Set the textcheckbox.Caption = "Apple"
ValueGet the checked stateIf checkbox.Value = True Then
ValueSet the checked statecheckbox.Value = False

 
 
The CheckBox is a simple control that allows the user set something to on or off. You will often see them used on web pages where you are asked to accept terms and conditions.

 
 
VBA Checkbox

 
 

Turning the CheckBox on or off

We can turn the CheckBox on or off by setting it to true or false

' Set the check on
CheckBoxTerms.Value = True

' Set the check off
CheckBoxTerms.Value = False

 
 

Checkbox Event with example

If we want to create an action when the user clicks on the checkbox then we create a checkbox event. This is simply a sub that runs when the checkbox is clicked.

 
 
To create this event simply click on the checkbox in design mode and you will get the following

Private Sub CheckBoxTerms_Click()

End Sub

 
 
The following code shows an example of how we use it

Private Sub CheckBoxTerms_Click()
 
    If checkboxTerms.Value = True Then
       buttonOk.Enabled = True
    Else
       buttonOk.Enabled = False
    End If
 
End Sub

 
 

The Label

 

The Label Cheat Sheet

FunctionOperationExample
TextGet\Set the texttextbox1.Text = "Apple"

The label is the most simple control. Generally speaking, we don’t refer to it in the code. It is used to label the controls or display a short notice.

 
 

Setting the Label Text

You can set the text of the Label in the code using the Caption property

LabelAddress.Caption = "Customer Address"

 
 

The TextBox

 
 

The TextBox Cheat Sheet

FunctionOperationExample
TextSet the texttextbox1.Text = "Apple"
TextGet the textsFruit = textbox1.Text
ValueSet the texttextbox1.Value = "Apple"
ValueGet the textsFruit = textbox1.Value

 
 

Setting the Textbox Text

The textbox is used to allows the user to enter text. We can read or write from a text box as follows

TextBoxNotes.Value = "It was the best of times."

sNotes = TextBoxNotes.Value

 
 
The textbox has properties Text and Values. These are the same thing.

From MSDN: For a TextBox, any value you assign to the Text property is also assigned to the Value property.

 
 
The problem with the text box is that the user can enter anything. If the user is entering basic text then this is fine. If the text is to be used for a calculation or for looking up something then we need to validate it.

For example, if the user is going to pick a year between 2010 and 2019 we should use a ComboBox/Listbox that only contains valid years. Then we don’t need to validate the format and range of the user’s entry.

 
 

Making a TextBox numeric only

The following code prevents the user entering anything other than a number in the textbox

Private Sub textboxComments_KeyPress( _
            ByVal KeyAscii As MSForms.ReturnInteger)
         
    Select Case KeyAscii
        Case Is < vbKey0, Is > vbKey9
            KeyAscii = 0
            Beep
    End Select
         
End Sub

 
 

Using a Date Control

If you the user to select a date you can use the MonthView control. It is one of the additional controls that comes with Visual Basic. It works quite well and looks like the standard date picker you see in most applications.

To add the MonthView control:

  1. Go the the Visual Basic editor and make sure the Toolbox is visible(View->Toolbox if it’s not visible).
  2. Select Tools and then Additional Controls from the menu.
  3. Place a check on Microsoft MonthView Control, Version 6.0.
  4. The MonthView control will now appear on the Toolbox.

 
 
To get the user selection from the MonthView control you can use the DateClick event as the following code shows

Private Sub MonthView1_DateClick( _	 	 
     ByVal DateClicked As Date)	 	 
 	 	 
    ' Store date in textbox	 	 
    TextBox1.Value = MonthView1.Value	 	 
 	 	 
End Sub	 	 

 
 
For more information on the MonthView see these links:

Issues adding the MonthView – see top answer on this StackOverflow page

MSDN – Using the MonthView Control

 
 

The ComboBox

 
 

The ComboBox Cheat Sheet

FunctionOperationExample
AddItemAdd an itemlistbox.AddItem "Spain"
ClearRemove all Items combo.Clear
ListAdd a range of itemscombo.List = Range("A1").Value
ListCountGet the number of itemscnt = combo.ListCount
ListIndexGet/set selected itemIdx = combo.ListIndex
combo.ListIndex = 0
ListRowsGet/set number of items displayed NoItems = combo.ListRows
combo.ListRows = 12
RemoveItemRemove an item combo.RemoveItem 1
ValueGet the value of selected ItemDim sCountry As String
sCountry = combo.Value

 
 
The ComboBox is used to allow the user to select an item from a list. It is very similar to the listbox. The main difference is the listbox allows multiple selections.

In most cases we want to do four things with the ComboBox\ListBox

  1. Fill it with data when the Form is loaded
  2. Preselect an item.
  3. Retrieve the currently selected item(s).
  4. Perfom an action when the user selects a different item.

 
 

Filling the Combobox with data

We can fill the combobox one item at at a time using the AddItem property.

comboBoxFruit.AddItem "Apple"
comboBoxFruit.AddItem "Pear"

 
 
You would normally use AddItem in a loop where you are checking each item before adding it

Dim cell As Range
' Fill items with first letter is A
For Each cell In Sheet1.Range("A1:A50")
    If Left(cell.Value, 1) = "A" Then
        comboBoxFruit.AddItem cell.Value
    End If
Next

 
 

Filling the ComboBox from a range

If you want to fill the ComboBox from an entire range you can do it in one line of code

comboBoxFruit.List = Sheet1.Range("A1:A5").Value

 
 
Normally when you fill a ComboBox you want to clear the existing contents first

' Clear any existing item
comboBoxFruit.Clear
' Fill the ComboBox
comboBoxFruit.List = Sheet1.Range("A1:A5").Value

 
 

Filling the ComboBox – No duplicates

If our range has multiple entries then we want to avoid adding the same item multiple times. We can do this using a Dictionary

Sub TestDuplicates()

    ' clear existing values
    comboBoxFruit.Clear
    
    ' Fill given ComboBox from given range ignoring duplicates
    FillComboNoDuplicates comboBoxFruit, Sheet1.Range("A1:A10")
    
End Sub

Sub FillComboNoDuplicates(cbo As ComboBox, rg As Range)
    
    ' Create dictionary
    Dim dict As Object
    Set dict = CreateObject("Scripting.Dictionary")
    
    Dim cell As Range, sItem As String
    ' Go through each item in range
    For Each cell In rg
        sItem = Trim(cell.Value)
        ' check if item already exists in dictionary
        If dict.Exists(sItem) = False Then
            ' If doesn't exist then add to dictionary and combobox
            dict.Add sItem, 1
            cbo.AddItem sItem
        End If
    Next
    
    ' Clean up dictonary as we no longer need it
    Set dict = Nothing

End Sub

 
 

VBA ComboBox – Full Example 1

The easiest way to show how these work is with an example. Imagine we have a list of countries and their capitals in cells A1:B196.

 
 
VBA Combobox

 
 
We want the user to select any country. When they do our UserForm will display the capital of that country. The screenshot below shows and example of this

 
 
VBA Combobox

 
 
The first thing we want to do is fill the countries ComboBox when the form loads. We do this using the UserForm_Initialize event which we looked at in the first post on VBA UserForms.

Private Sub UserForm_Initialize()
    
End Sub

 
 
We can use the following code to fill the ComboBox from a range and set the selected item to be the first one. (Note we don’t need to clear the ComboBox here as the Initialize event is only used once – when the UserForm is created.)

Private Sub UserForm_Initialize()
    
    ' Add array to combobox
    ComboBoxCountry.List = Sheet1.Range("A1:A196").Value
    
    ' Set the first item in combobox
    ComboBoxCountry.ListIndex = 0
    
End Sub

 
 
When the user selects a country we want to display the capital city in the textbox. We use the Change Event of the ComboBox. To create this we simply double click on the ComboBox and it will be automatically created.

Private Sub ComboBoxCountry_Change()
    
    ' Get the value from the combo box
    Dim sCountry As String
    sCountry = ComboBoxCountry.Value
    
    ' Get the range
    Dim rg As Range
    Set rg = Sheet1.Range("A1:B196")
    
    ' Use VLookup to find the capital of the country
    TextBoxCapital.Value = _
        WorksheetFunction.VLookup(sCountry, rg, 2)
    
End Sub

 
 
When the user clicks Ok we write the selected values to the Results worksheet

Private Sub buttonOK_Click()
    
    With shResult

        ' Write the country the was selected
        .Range("A1") = ComboBoxCountry.Value
        
        ' Write the postion of the selected country
        .Range("A3") = ComboBoxCountry.ListIndex

        ' Write the capital of the country
        .Range("A2") = TextBoxCapital.Value

    End With

    ' Close the form
    Unload Me
    
End Sub

 
 

VBA ComboBox – Full Example 2

A very commmon task to perform is to update a second ComboBox based on the selection of the first.

 
 
VBA Controls

 
 
Imagine we have two ComboBoxes – one contains the name of a country and one has a list of three cities from that country.

 
 
VBA Combobox Cities

 
 
When the user selects a country we update the city ComboBox with the cities from that country.

 
 
Our data is stored as follows

VBA Combobox City

 
 
Anytime the Country ComboBox value is set to a country we update the City ComboBox to contain the three cities from that country. This happens in two places

  1. When we load the country combo box – the Initialize Event
  2. When the user selects a country – the Change Event

 
 
The code for these is as follows

Private Sub UserForm_Initialize()
    
    ' Add array to combobox
    ComboBoxCountry.List = shCity.Range("A1:A4").Value
    ComboBoxCountry.ListIndex = 0
    
    ' Fill the city ComboBox
    FillCityCombo ComboBoxCountry.ListIndex
    
End Sub

Private Sub ComboBoxCountry_Change()
    ' Fill the city ComboBox
    FillCityCombo ComboBoxCountry.ListIndex
End Sub

 
 
In both cases we call our FillCityCombo Sub to fill the city ComboBox. It takes one parameter which is the position of the current country selection.

We use the position value to count from the top row of our worksheet range.

Sub FillCityCombo(ByVal row As Long)

    ' Get the city range from the given row
    Dim rgCities As Range
    Set rgCities = shCity.Range("B2:D2").Offset(row)
    
    ' Clear current city list
    ComboBoxCity.Clear
    
    ' We transpose the range of columns e.g. B2:D2 to rows so 
    ' we can add to the ComboBox
    ComboBoxCity.List = _
            WorksheetFunction.Transpose(rgCities)
            
    ' Set the first city in list
    ComboBoxCity.ListIndex = 0

End Sub

 
 

The ListBox

The ListBox is used in almost the same way as the ComboBox. The code in the ComboBox section above will work for the ListBox also.

 
 

The ListBox Cheat Sheet

FunctionOperationExample
AddItemAdd an itemlistbox.AddItem "Spain"
ClearRemove all Itemslistbox.Clear
ColumnCountSet the number of visible columnsComboBox1.ColumnCount = 2
ColumnHeadsMake the column row visibleComboBox1.ColumnHeads = True
ListRange to Listbox
ListBox to Range
Listbox.List = Range("A1:A4").Value
Range("A1:A4").Value = Listbox.List
ListCountGet the number of itemscnt = listbox.ListCount
ListIndexGet/set selected itemIdx = listbox.ListIndex
combo.ListIndex = 0
RemoveItemRemove an itemlistbox.Remove 1
RowSourceAdd a range of values from a worksheet ComboBox1.RowSource = Sheet1.Range("A2:B3").Address
ValueGet the value of selected ItemDim sCountry As String
sCountry = listbox.Value

We can use the ListBox the same way as we used the ComboBox. The difference is how they are displayed

  • The ListBox displays a list of available items to select.
  • The ComboBox only displays the selected item. You have to click on the ComboBox to see the other available items.

 
 
The other major difference between them is that the ListBox allows multiple selections and the ComboBox doesn’t.

 
 
VBA ListBox multi

 
 
We can get all the selected items in the ListBox by reading through all the items and checking if each one is selected. In the code below we add all the selected items to a Collection.

' USERFROM CODE

' OK click event
Private Sub buttonOk_Click()
    ' Get the user selections
    Set m_CollCountries = GetSelections
    ' Hide the UserForm
    Hide
End Sub

' Returns the collection of countries
Property Get Countries() As Collection
    Set Countries = m_CollCountries
End Property

' Get the selections from the ListBox
Private Function GetSelections() As Collection
    
    Dim collCountries As New Collection
    Dim i As Long
    
    ' Go through each item in the listbox
    For i = 0 To ListBoxCountry.ListCount - 1
        ' Check if item at position i is selected
        If ListBoxCountry.Selected(i) Then
            ' Add item to our collection
            collCountries.Add ListBoxCountry.List(i)
        End If
    Next i
    
    Set GetSelections = collCountries
    
End Function

 
 

' MAIN PROCEDURE CODE

' Sub to display the UserForm
Sub DisplayMultiCountry()
    
    Dim frm As New UserFormCountryMulti
    frm.Show

    ' Print the collection
    PrintCollection frm.Countries
    
End Sub

' Sub used to print a collection to the Immediate Window(Ctrl + G)
Public Sub PrintCollection(ByRef coll As Collection)
    
    Debug.Print "The user selected the following countries:"
    Dim v As Variant
    For Each v In coll
        Debug.Print v
    Next
    
End Sub

 
 
That concludes the two posts on UserForm(see first one here).

I hope you found them of benefit. If you have any questions or queries please feel free to add a comment or email me at Paul@ExcelMacroMastery.com.

 
 

What’s Next?

If you want to read about more VBA topics you can view a complete list of my posts here. I also have a free eBook(see below) which you will find useful if you are new to VBA.

If you are serious about mastering VBA then you may want to check out Build 11 Full VBA Applications

 
 

Get the Free eBook

How To Ace the 21 Most Common Questions in VBA

Please feel free to subscribe to my newsletter and get exclusive VBA content that you cannot find here on the blog, as well as free access to my eBook, How to Ace the 21 Most Common Questions in VBA which is full of examples you can use in your own code.

Free VBA eBook

 
 

14 comments

  1. Hi Paul,

    Just noted a error in the checkbox text:

    ‘ Set the check on
    CheckBoxTerms.Value = True

    ‘ Set the check off
    CheckBoxTerms.Value = True ‘<<<< should be False.

    Best regards,
    Ludo

  2. Hi,
    for num: case asc(“0”) to asc(“9”),
    for alpha: case asc(“a”) to asc(“z”), asc(“A”) to asc(“Z”),
    for dates: case asc(“/”) to asc(“9”) 🙂

  3. Though I only had a quick look, I think application.EnableEvents =… should be used in order not to trigger form control events … especially of hidden forms especially when they depend on ranges.

  4. Hi Paul,

    I’m rewriting a application (Add-In [13 userforms]) for the company and i do have a question regarding the userform(s).

    what i do, is as follow:

    I check if a configuration file (INI file) is present.
    if not, I show a configuration userform (8 Page tabs – 73 controls) .
    I enter all the needed data into the appropriate textboxes / listboxes / checkboxes and write this data into a Configuration.INI file.
    The data is also placed into the Add-In worksheet / worksheets.
    I unload the userform.

    The next time i use the add-in, the configuration.INI file is present, so, i read the INI file into the Add-In worksheet(s).

    The Add-In worksheet(s) use named ranges.

    When i need data (names, numbers, file paths, …), i’ll read the corresponding worksheet named range.
    No need to load the userform.

    I see you use following construction in your main procedure code:
    Dim frm As New UserForm
    and the accompanying property Get / Let in the userform module.

    I would like to know if this approach could add benefits against the way i’m working now.

    How would you approach this?
    Or am I doing it the right way?

    I noticed also, if I use your approach with the userforms, and need data from one userform to use in an other sub that i needed to
    define the userform on top of a regular module as public like:
    Public MyUserform As New frmConfiguration
    Then i can use code like ConfigPath = MyUserform.ConfigPath where ever i need it in the whole project.

    Best regards,
    Ludo

    1. Hi Ludo,

      The way you are approaching is mostly okay but using the workbook for temporary storage can be slow and awkward.

      I would normally have a Class module for storing the settings.
      When the application loads you would read from the ini file to the class. When the application is finished you would write the values back to the file.

      When the UserForm is displayed you read from the class to the UserForm controls. When the user clicks Ok you write any changed values back to the class and unload the UserForm.

      If you have further questions about this drop me an email.
      Regards
      Paul

  5. Hi Paul,
    Here i’m back with a question regarding Textbox and Pages on a userform.

    I have a Userform with a Close button, a Previous and Next button on the bottom of it. Above these buttons i have 7 Pages (MultiPage object). What i notice is following behaviour: when i enter text into the last textbox on the Page, the Change event fires (= normal) , so i can do some stuff here. When i click then on the Next/Previous button, who are outside the Page, the textbox Exit event doesn’t fire. Is there a way to fire the textbox Exit event in the Page when click on a button outside the Page?

    Best regards,
    Ludo

  6. Hi Paul

    The data generally are never ordered, should include the “False” argument in the formula, to avoid errors in these cases.

    TextBoxCapital.Value = WorksheetFunction.VLookup(sCountry, Rg, 2, False)

    Regards.

  7. Hi Paul:

    In a similar vein to Ludo’s question on 19 May ’16, I am investigating the [Public Property] Let statement to pass a variable into a Userform. However, I am attempting to use that variable to affect display of controls on the Userform. There are two checkboxes on the form, and I would like to pass an integer (set to 0, 1 or 2) to determine display of neither, the first or both checkboxes, by their .Visible switches.

    The questions are:
    – Can the Let statement be used in determining control display?
    – If so, where is the statement placed in the Userform code?
    – I have attempted to place the Let statement either in the Initialize or Activate procedures.
    – this action changes the End Sub statement to End Property, which I manual correct.
    – upon compiling, the debugger stops at the line in the procedure before the Let statement, claiming an unexpected End Sub.

    Any advice you can provide would be welcome.

    Thank you.

    1. Hi Quinton,

      You can use the Let property to pass a value to the UserForm. You can then store this value in a variable in the UserForm.

      UserForm code

      Private m_lDisplay As Integer
      
      Public Property Let Display(ByVal lDisplay As Long)
          m_lDisplay = lDisplay
      End Property
      

      Calling the UserForm

      Dim frm As New UserForm1
      
      ' pass the display value
      frm.Display = 1
      
      ' display the userform
      frm.Show
      
      1. Hi Paul:

        Your answer gave me enough to implement my plan. I hadn’t seen the Private variable declaration and the assignment of the passed value to the form’s variable (m_lDisplay) in other reference examples. Once I determined that setting the control visibility had to be done within the Let statement, it all worked correctly.

        As a follow-up question, the definition of the ByVal passed variable (lDisplay) as a Long (integer), then assigning it to the form’s Int variable (m_lDisplay), is that done as a pre-caution, or is it a necessity when passing integers in?

        Thanks for the help.

        Quinton

Leave a Reply

Your email address will not be published. Required fields are marked *