Excel VBA Classic Excel VBA 2010 Excel VBA 365 Excel VBA Examples About Us

Lesson 23: ListBox, ComboBox and Toggle Button


In this lesson, we will deal with ListBox, ComboBox and Toggle Button.

23.1 ListBox

The function of the ListBox is to present a list of items where the user can click and select the items from the list. To add items to the list, we can use the AddItem method. To clear all the items in the ListBox, you can use the Clear method. The usage of Additem method and the Clear method is shown Example 23.1.

Example 23.1

Private Sub CommandButton1_Click() 
 For x = 1 To 10 
 ListBox1.AddItem "Apple" 
 Next 
End Sub

'To clear the ListBox

Private Sub CommandButton2_Click() 
 For x = 1 To 10 
 ListBox1.Clear  
 Next 
End Sub

vba2010_figure23.1
Figure 23.1

23.2 ComboBox

The function of the ComboBox is also to present a list of items where the user can click and select the items from the list. However, the user needs to click on the small arrowhead on the right of the ComboBox to see the items which are presented in a drop-down list. In order to add items to the list, you can also use the AddItem method.

Example 23.2

Private Sub CommandButton1_Click() 
 ComboBox1.Text = "Apple" 
 For x = 1 To 10 
 ComboBox1.AddItem "Apple" 
 Next  
End Sub
 

'To clear the ComboBox

Private Sub CommandButton2_Click() 
 ComboBox1.Clear 
End Sub

The Output

vba2010_figure23.2
Figure 23.2

23.3 Toggle Button

Toggle button lets the user switches from one action to another alternatively. When the Toggle button is being depressed, the value is true and when it is not depressed, the value is false. By using the If and Else code structure, we can thus switch from one action to another by pressing the toggle button repeatedly.

Example 23.3

In this example, the user can toggle between apple and orange as well as font colors.

Private Sub ToggleButton1_Click () 
 If ToggleButton1.Value = True Then 
 Cells (1, 1).Font.Color = vbRed 
Else 
 Cells (1, 1) = "Orange" 
 Cells (1, 1).Font.Color = vbBlue 
End If 
End Sub

View the animated image in Figure 23.3

Figure 23.2

❮ Previous Lesson Next Lesson ❯


Copyright ® 2008 Dr.Liew Voon Kiong . All rights reserved   [Privacy Policy]

Contact: Facebook Page