Form controls in excel vba

Excel Form Controls In VBA Banner

I wouldn’t touch those controls….

One of the coolest things about Excel is the ability to add Form Controls. Form Controls are interactive UI elements you have probably seen many times. They can be:

  • Command Buttons
  • Combo boxes
  • Checkboxes

Form Controls are great because they are intuitive ways to interact with a piece of software that everyone can understand. Implementing them in an Excel sheet can really open up the complexity options in your project.

But, how do you use them? Form Controls can bring a lot to your application, but they are a little more complicated to configure and use in VBA. In this blog post, I am going to go through each Form Control and explain how to configure it, interact with it, and use it in a piece of code.

Let’s get started!

Adding Form Controls To A Spreadsheet

To add Form Controls to a spreadsheet, you will need to enable the Developer section of the toolbar:

Excel Developer Tab

If you do not see this tab on your toolbar, navigate to File –> Options:

Excel Options

And go to the ‘Customize Ribbon’ section:

Excel Customize Ribbon

Add the Developer option to your Main Tabs and click ‘OK.’ You should then be set to add Form Controls.

Command Button Form Controls

The first option you have for Form Controls is the command button. This is one of the most basic controls found in any application.

Excel Form Control Command Button

It is simply a button that you click on to trigger some other action. You can also format the label on the button and give it a few different colors and sizes. To add a command button to a sheet, go to your ‘Developer’ tab and under ‘Insert,’ select the first option:

Insert Excel Form Control Command Button

Once selected, your cursor will change into a crosshair. You can now click and drag a rectangle onto your sheet, and the rectangle will be the size of your button:

Insert Excel Form Control Command Button 1

When you let go of your mouse, Excel will automatically open a window that will ask you if you want to link a macro to this button:

Excel Form Control Command Button Macro

In this case, thus button was the 8th Form Control I added to this sheet, so it shows up automatically as ‘Button8.’ When you go further into the macro by clicking ‘New,’ you will see the following:

Sub Button8_Click()

End Sub

With this, you can now create an event for your button to trigger when its clicked. Let’s create a button that puts a hard-coded value into a cell:

Sub Button8_Click()
    ActiveSheet.Cells(1, 1).Value = "Button was clicked!"
End Sub
Excel Form Control Command Button On Sheet
After the macro ran

Pretty easy right!? You can change the macro that gets fired off of this button by right-clicking on it and selecting ‘Assign Macro,’ and then choose the macro you want.

Command Button in VBA

Having a button and a macro are great, but what if you wanted to access your button in a macro? Well, paste the following code below and you can paste the button text in a cell:

Sub Button8_Click()
    ActiveSheet.Cells(1, 1).Value = ActiveSheet.Shapes("Button 8").OLEFormat.Object.Caption
End Sub

It’s important to note that there is a space between ‘Button’ and ‘8’ in the above macro. To access Form Controls on your sheet in VBA, you need to use the syntax:

Activesheet.Shapes([Optional Object Name]).OLEFormat.Object

The above syntax will then let you access a Form Controls properties and methods. For the command button, its properties and methods are listed here.

In this example, I am using the ‘Caption’ property to get the text on the button and paste it in a cell:

Excel Form Control Command Button In VBA
After the macro ran

Ta-da! You can build some really advanced logic on your spreadsheets with controls once you can access them in VBA.

Combo Box Form Controls

The combo box, also known as a drop-down list, is a box with an arrow that shows you options when clicked. Clicking one of the options select it as the controls value:

Excel Form Control Combo Box

To add a combo box to your spreadsheet, click on the ‘Insert’ option under the ‘Developer’ ribbon and select the second option:

Insert Excel Form Control Combo Box

Now, when you select this option, your cursor will, again, turn into a crosshair. Draw the size of the rectangle you want the combo box to be and it will render on the page.

You’ll notice you are not prompted to assign the combo box to a macro once it’s rendered. Normally, the combo box is not designed to trigger a macro, but it can be. Before we get to that, let’s configure our combo box. Right-click on it and select ‘Format Control’ and navigate to the ‘Control’ tab:

Excel Form Control Combo Box Configuration

The tabs before control allow allow you to configure the visuals of the combo box, but the Control tab is where you can configure its values and what cell you can see the selected value index in.

In some other cells on the sheet, type in the values you want in the combo box, each in a separate cell, and link them to your input:

Excel Form Control Combo Box Options
Options for the combo box

Select a single cell for the ‘Cell link’ option, and that cell will get the index of the combo box value selected, and it will update every time to combo box is updated:

Excel Form Control Combo Box Cell Link
Cell to see the index of the value

Now, try out your combo box!

Excel Form Control Combo Box Selecting An Option

Selecting an option
Excel Form Control Combo Box Option Selected
Option selected

Pretty cool! You can also assign a macro to a combo box in the same way you can to a Command Button, and it will fire every time the value of the combo box is updated.

Combo Box In VBA

Having a combo box is great and being able to assign a macro to it is also helpful. But what if you wanted to put some more complex logic in the macro? Say you only wanted the macro to do something when a certain combo box value was selected. To get the value of a combo box in VBA:

Sub DropDown11_Change()
    Dim index As Long
    
    index = ActiveSheet.Shapes("Drop Down 11").OLEFormat.Object.ListIndex
    If index = 2 Then
        ActiveSheet.Cells(1, 4).Value = ActiveSheet.Shapes("Drop Down 11").OLEFormat.Object.List(index)
    Else
        ActiveSheet.Cells(1, 4).Value = ""
    End If
End Sub

The above code will get the index of the combo box value when it changes. If that index is 2, we write the value of the list item in our cell. If not, it clears the cell out:

Excel Form Control Combo Box In VBA
Not the option we want

When we select the second option:

Excel Form Control Combo Box In VBA Right Selection
The option we want!

And picking something else again:

Excel Form Control Combo Box In VBA Wrong Option
Not the right option again….

As you can see, you can do a lot with VBA and Form Controls once you get the hang of it. The other methods and properties available for a combo box can be seen here.

Checkbox Form Controls

Everyone has used a checkbox when interacting with a web app. A checkbox give users a simple way to specify a ‘True’ or ‘False’ value:

Excel Form Control Checkbox

To insert a check box on an Excel sheet, select the ‘Insert’ option under the ‘Developer’ tab and select the third option:

Insert Excel Form Control Checkbox

When you select it, your cursor will turn into a crosshair. Click on the sheet where you want your checkbox to render and it will appear:

Excel Form Control Checkbox On Sheet

For a checkbox, the most important configuration option is the ‘Cell link.’ You can specify a cell to hold the value of the checkbox as it changes:

Excel Form Control Checkbox Configuration
Selecting our cell link to show the value

Specify the cell you want to hold the checkbox value and:

Excel Form Control Checkbox Cell Link
The cell value!

Pretty cool! You can also assign a macro to checkbox and it will fire upon change.

Checkbox In VBA

A checkbox is very handy, but in a macro, the most important part of it is getting the checkbox value. Say you wanted to fire a macro and check that checkbox value to build some interesting logic:

Sub CheckBox12_Click()
    Dim checkboxvalue As Integer
    
    checkboxvalue = ActiveSheet.Shapes("Check Box 12").OLEFormat.Object.Value
    Debug.Print (checkboxvalue)
End Sub

If you run this macro, you can see in the VBA window that a value of True = 1 and a value of False = -4146. Why? I’m not sure, but you can use it for whatever logic you need!

Excel Form Control Checkbox In VBA
The true and false values as I was checking and unchecking the box

You can see other properties and methods of the checkbox Form Control here.

Iterating Over Multiple Form Controls

Once you start using Form Controls in VBA, you can use the Shapes() method to get all the controls on a page and start iterating over them to see what;s on your sheet and how you can get their properties:

Sub ShapeNames()
For Each obj In ActiveSheet.Shapes()
    Debug.Print (obj.OLEFormat.Object.Name)
Next
End Sub

Running the above code for my sheet, I get:

Excel Form Controls Iteration
All my form controls

The above code can be very helpful in figuring out what’s on your sheet and how you can reference it. Try combining From Controls with some of the other VBA code to make a dynamic, living application. Happy macro’ing!

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

The Webinar

If you are a member of the website, click on the image below to view the webinar for this post.

(Note: Website members have access to the full webinar archive.)

vba userform2 video

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 UserForm 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

Control Description
CheckBox Turn item on/off
ComboBox Allows selection from a list of items
CommandButton Click to perform action
Label Displays text
ListBox Allows selection from a list of items
Textbox Allows 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.

Function Operation Example
Enabled Enable/Disable control combobox.Enabled = True
textbox.Enabled = False
SetFocus Sets the focus to the control
(cannot use with the Label)
combobox.SetFocus
Visible Show/Hide control combobox.Visible = True
textbox.Visible = False
' https://excelmacromastery.com/
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

Function Operation Example
Caption Get/Set the text checkbox.Caption = «Apple»
Value Get the checked state If checkbox.Value = True Then
Value Set the checked state checkbox.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

' https://excelmacromastery.com/
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

Function Operation Example
Text GetSet the text textbox1.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

Function Operation Example
Text Set the text textbox1.Text = «Apple»
Text Get the text sFruit = textbox1.Text
Value Set the text textbox1.Value = «Apple»
Value Get the text sFruit = 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

' https://excelmacromastery.com/
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

' https://excelmacromastery.com/
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

Function Operation Example
AddItem Add an item listbox.AddItem «Spain»
Clear Remove all Items combo.Clear
List Add a range of items combo.List = Range(«A1»).Value
ListCount Get the number of items cnt = combo.ListCount
ListIndex Get/set selected item Idx = combo.ListIndex
combo.ListIndex = 0
ListRows Get/set number of items displayed NoItems = combo.ListRows
combo.ListRows = 12
RemoveItem Remove an item combo.RemoveItem 1
Value Get the value of selected Item Dim 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 ComboBoxListBox

  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

' https://excelmacromastery.com/
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.)

' https://excelmacromastery.com/
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.

' https://excelmacromastery.com/
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

' https://excelmacromastery.com/
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

' https://excelmacromastery.com/
Private Sub UserForm_Initialize()
    
    ' Add array to combobox
    ComboBoxCountry.List = shCity.Range("A2:A5").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.

' https://excelmacromastery.com/
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

Function Operation Example
AddItem Add an item listbox.AddItem «Spain»
Clear Remove all Items listbox.Clear
ColumnCount Set the number of visible columns ComboBox1.ColumnCount = 2
ColumnHeads Make the column row visible ComboBox1.ColumnHeads = True
List Range to Listbox
ListBox to Range
Listbox.List = Range(«A1:A4»).Value
Range(«A1:A4»).Value = Listbox.List
List Update a column value Listbox.List(1,2) = «New value»
ListCount Get the number of items cnt = listbox.ListCount
ListIndex Get/set selected item Idx = listbox.ListIndex
combo.ListIndex = 0
RemoveItem Remove an item listbox.Remove 1
RowSource Add a range of values from a worksheet ComboBox1.RowSource = Sheet1.Range(«A2:B3»).Address
Value Get the value of selected Item Dim 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
' https://excelmacromastery.com/
Private m_CollCountries As Collection

' 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
' https://excelmacromastery.com/
' 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?

Free VBA Tutorial If you are new to VBA or you want to sharpen your existing VBA skills then why not try out the The Ultimate VBA Tutorial.

Related Training: Get full access to the Excel VBA training webinars and all the tutorials.

(NOTE: Planning to build or manage a VBA Application? Learn how to build 10 Excel VBA applications from scratch.)

Excel VBA — ActiveX Controls, Form Controls & AutoShapes on a Worksheet

————————————————————————————————

Contents:

Forms in Excel

ActiveX controls, Form controls & AutoShapes in an Excel Worksheet

Shape object & OLEObject object

ActiveX Controls in VBA

Add an ActiveX Control, a Form Control or an AutoShape, in Worksheet

Illustrating Form Controls, ActiveX Controls & AutoShapes:

Button (Form Control); Command Button (ActiveX Control)

Check Box — Form Control or ActiveX Control

List Box & Combo Box — Form Control / ActiveX Control

Option Button — Form Control or ActiveX Control

Toggle Button — ActiveX Control

ScrollBar & SpinButton Controls — Form Control or ActiveX Control

TextBox — ActiveX Control

Label — Form Control or ActiveX Control

Illustrating Auto Shapes, Add a connector

————————————————————————————————

You can create various types of Forms in Excel, which are documents having a standard structure & format & help to organize, capture & modify data. Type of forms which can be created in Excel include: Data Form, Worksheet containing Form controls & ActiveX controls, & UserForms in VBA. You may use a Form individually, or combine them in various manners for your suitability. In this section we explain the Shape object & OLEObject object, and illustrate using ActiveX Controls, Form controls & AutoShapes in an Excel Worksheet.

Built-in Excel Data Form

Using a Data Form is an easy way to display or enter all information in one row in a table or in a range, without scrolling or moving between columns. A Data Form is best used: (i) when your spreadsheet is too big & you constantly scroll back & forward to display & enter data; (ii) when you want to view a simple form containing text boxes labeled on column headings, wherein each text box displays the row data for each column; & (iii) when you do not need advanced form features like a list box or spin button.

Excel has a built-in Data Form which can be generated automatically for your table or range listing all the table fields: all columns headers are displayed as labels for text boxes in one dialog box; each text box displays the row data for each column upto a maximum of 32 columns; you may enter new rows, update or delete rows, scroll through the records using the scroll bar, find previous or next rows based on specified criteria or cell contents; only formula result is displayed in text box for cells with formulas; Data Form cannot be printed though you may use the PrtScr button to save an image.

Refer Image 1a: Cell J3 has been selected, and Data Form is generated by clicking on ‘Form’ button in the Quick Access Toolbar (to Add the Form button to the Quick Access Toolbar: click the arrow next to the ‘Quick Access Toolbar’ > click ‘More Commands’ > click ‘All Commands’ in the ‘Choose commands from box’ > select the ‘Form’ button > click ‘Add’ > click ‘OK’). Image 1a displays the first row data in the Data Form: to navigate through one row at a time you may use the vertical scroll arrows in the center or click the Find Prev or Find Next (clicking the scroll bar in the area between the arrows will move through 10 rows in one go); to find the next or previous row as per criteria or cell contents — click Criteria, enter criteria (say Male in the Gender text box), click Find Next, and then the next row corresponding to Male Gender will be displayed; click on New or Delete to add new row or delete existing row; to change row data — press TAB to move to the next field in the row & press SHIFT+TAB to move to the previous field, enter new content in the field or text box, press Enter and the data will be updated & you will go the next row — clicking on Restore before pressing Enter will restore the old content; click Close to close the Data Form. Note that only formula result is dsplayed in text box for BMI column header whose cells have formulas, wherein the formula cannot be changed using the data form. When you enter Criteria, you may use the following wildcard characters: ? (question mark) > to find any single character viz. T?m finds both Tim & Tom; * (asterik) > to find any number of characters viz. *Active finds both InActive and VeryActive; ~ (tilde) followed by ?, *, or ~ > to find a question mark, asterik or tilde viz. When~? finds When?.

UserForms in Excel VBA

UserForm is a customized user interface (viz. custom dialog box), developed in VBA. It enables a user to interact, using a Form, in an organized and logical manner, to make data entry or for data retrieval with an Excel worksheet or to run a VBA application. UserForm acts as a container in which you add multiple ActiveX controls, each of which has a specific use and associated properties. By itself, a UserForm will not be of much use unless ActiveX controls are added to it which are the actual user-interactive objects. Refer our separate section on Userforms for detailed illustration.

ActiveX controls, Form controls & AutoShapes in an Excel Worksheet

Another type of form is a worksheet: you can enter, format & view data in worksheet cells which can also be used as text boxes or labels by adjusting their height / width, so as to function as a data form; a worksheet can be used as an advanced data form by using its various built-in features which behave like controls, viz. comments, data validation, hyperlinks, background images, conditional formatting, embedded charts, AutoFilter, etc.

Two types of controls are available in Excel — Form controls & ActiveX Controls. Besides these controls, you can also add objects from the Drawing tools, like AutoShapes, WordArt, SmartArt graphic or text boxes. These controls & drawing tools add flexibility to using the worksheet as they can be linked to & work in tandem with worksheet cells — a check box control can be used to make multiple selections, an option button control allows to choose a single option from within a set of mutually exclusive choices, a spin button control facilitates to enter a number, & so on. These controls & objects can be displayed with associated labels / text & independent of row or column outlines / sizes, these may be linked to worksheet cells with our without using vba code, and can float freely or else move & resize with cells, for example, in respect of a command box control you may want to keep it the same size & in a specific location always so that when its underlying cells’ size changes or cells are moved, the command box retains its size & position.

Form Controls

Form controls are used to reference & interact with cell data in a worksheet — they are used to easily place values in worksheet cells, without programming, and they facilitate to compel users choose from defined options. VBA code is not required to use Form controls, but you can assign a macro to a control so that on clicking the control the macro will be executed. Form controls can also be added to chart sheets, but not to UserForms or to control events. For example, you may link a worksheet cell to a spin button, so that clicking on the up arrow will increase the value (increment a number, time or date) in the linked cell while clicking on the down arrow will decrease the value — this will obviate the need for manual entry in the cell. The Form controls — ‘Text Field’, ‘Combo List — Edit’, ‘Combo Drop-Down — Edit’, ‘Run Dialog’ — can only be used in Excel version 5.0 dialog sheets & are not available in Excel 2007. The various Form controls are illustrated later in this section.

ActiveX Controls

ActiveX controls can be used with VBA code or without, either directly on worksheets, while some can be used only on VBA UserForms. ActiveX controls offer more flexibility as compared to Form controls as they have numerous properties which can be used to customize their functionality, appearance, fonts & other characteristics.

ActiveX controls have associated event procedures which are triggered on clicking the control. ActiveX controls can be used to control different events, so that you can write macros to execute the associated events. You can execute different actions specific to the option selected by the user to interact with the control. You cannot assign a macro to ActiveX controls similar to Form controls wherein clicking the control executes the macro. ActiveX controls cannot be added to chart sheets or to XLM macro sheets. ActiveX controls contained in your computer include Calendar Control 12.0 & Windows Media Player, as installed by Excel or other programs.

In Excel 2007 Form Controls & ActiveX Controls are available in the Controls group on the Developer tab of the Ribbon (Refer Image 1b), while in earlier versions they were available on toolbars.

Objects from the Drawing tools

In Excel 2007, under the Insert tab on the ribbon, you can insert an Object, Shape, Picture, SmartArt graphic, Chart, Text Box, WordArt, etc. in a worksheet. Right click on the object, shape or graphic you have inserted, and select Assign Macro which opens the Assign Macro dialog box from where you can select and assign a macro to the object. In this section, we limit our discussion to AutoShapes (we have a separate section which deals with Charts in detail). You can select from a set of ready-made shape types for an AutoShape object in vba, as specified in MsoAutoShapeType Enumeration, for use in your worksheet. VBA allows you to add shapes & objects which can be manipulated & formatted by resizing or rotating, adding text or caption & setting font, changing color, or adding 3D effects such as beveling & shadows, and assigning macros.

Shape object & OLEObject object

A Shape object represents an object in the drawing layer, such as an AutoShape, freeform, OLEobject or picture. Every excel worksheet  & chart sheet & excel chart has a drawing layer upon which drawing objects are placed. Both the Worksheet object & the Chart object both have a Shapes property that returns a Shapes collection ie. the Shapes object, which contains all the Shape objects in the worksheet or in the chart sheet. The you have the ShapeRange collection (ie. ShapeRange object), which represents a subset of shapes on a document — a ShapeRange object can contain a single shape, or a few shapes (viz. first, third & fifth shape out of a total of 8 shapes in a sheet), or it could represent all shapes in a document. The ShapeRange object allows you to set the properties of a subcollection of all Shape objects. We have now discussed 3 objects: (i) Shape object; (ii) Shapes object; & (iii) ShapeRange object.

An OLEObject object represents an ActiveX control or a linked or embedded OLE object on a worksheet. The OLEObjects collection (ie. OLEObjects Object) contains all the OLEObject objects on a single worksheet. Use the Worksheet.OLEObjects method to return either a single OLE object (an OLEObject ) or a collection of all OLE objects (an OLEObjects Object) — Syntax: Worksheet.OLEObjects(Index), where Index is the name or number of the OLE object. Use the OLEObjects.ShapeRange Property to return a ShapeRange object which represents the specified object or objects — a subset of shapes which can be a single shape, or a few shapes (viz. first, third & fifth shape out of a total of 8 shapes in a sheet), or it could represent all shapes. Note: OLE objects do not support many changes which can be made through ShapeRange. In Excel VBA, ActiveX controls are represented by OLEObject objects in the OLEObjects collection, so that ActiveX control properties can be set using the properties of an OLEObject object, but the OLEObject object is not used for Form Controls.

OLE — Object Linking and Embedding — is used to make content that is created in one program (ex. Microsoft Office Word) available in another program (ex. Microsoft Office Excel). OLE is supported by many different programs — only programs that are installed on your computer and which support OLE objects appear in the Object type box. Information may be copied as either a linked object or an embedded object — the prime difference between the two is where the data is stored & how the object is updated after it is placed in the destination file. Embedded objects are stored in the workbook in which they are inserted, & are not updated. Linked objects remain as separate files, & can be updated.

Shape.Type Property & Shape.FormControlType Property:

Use the Type Property of the Shape object to set or return the Shape Type, as per constants / values specified in the MsoShapeType Enumeration, Ex. the MsoShapeType constant msoFormControl indicates a Form Control, constant msoOLEControlObject indicates an OLE control object (ActiveX Control), and so on.

There is another property — FormControlType Property of the Shape object — which returns (read-only) the Control Type for a Shape object (per XlFormControl Enumeration) & this property is not valid for ActiveX controls but used only where the Shape.Type Property returns msoFormControl. Ex. the XlFormControl constant xlCheckBox represents a Check Box, constant xlListBox represents a List Box, and so on.

MsoShapeType Enumeration   XlFormControl Enumeration
MsoShapeType Value Description   XlFormControl Value Description
msoAutoShape 1 AutoShape       xlButtonControl      0 Button           
msoCallout 2 Callout   xlCheckBox 1 Check box
msoChart 3 Chart   xlDropDown 2 Combo box
msoComment 4 Comment   xlEditBox 3 Text box
msoFreeform 5 Freeform   xlGroupBox 4 Group box
msoGroup 6 Group   xlLabel 5 Label
msoEmbeddedOLEObject 7 Embedded OLE object   xlListBox 6 List box
msoFormControl 8 Form control   xlOptionButton 7 Option button
msoLine 9 Line   xlScrollBar 8 Scroll bar
msoLinkedOLEObject 10 Linked OLE object   xlSpinner 9 Spinner
msoLinkedPicture 11 Linked picture        
msoOLEControlObject 12 OLE control object        
msoPicture 13 Picture        
msoPlaceholder 14 Placeholder             
msoTextEffect 15 Text effect        
msoMedia 16 Media        
msoTextBox 17 Text box        
msoScriptAnchor 18 Script anchor        
msoTable 19 Table        
msoCanvas 20 Canvas        
msoDiagram 21 Diagram        
msoInk 22 Ink        
msoInkComment 23 Ink comment        
msoIgxGraphic 24 SmartArt graphic        
msoShapeTypeMixed -2 Mixed shape type        

Sub Shape_Type_FormControlType()

‘returns 12 indicating an OLE control object (MsoShapeType constant of msoOLEControlObject)

MsgBox Sheets(«Sheet1»).Shapes(«OptionButton1»).Type

‘returns the message «Check Box Form Control», indicating the shape is a Form Control & is a Check Box

If Sheets(«Sheet2»).Shapes(«Check Box 1»).Type = msoFormControl Then

If Sheets(«Sheet2»).Shapes(«Check Box 1»).FormControlType = xlCheckBox Then MsgBox «Check Box Form Control»

End If

End Sub

Example: for Auto Shapes, illustrating Shapes object, Shape object & ShapeRange object

Sub AutoShape_ShapesObj_ShapeObj_ShapeRangeObj()
‘illustrating Auto Shapes — Shapes object, Shape object & ShapeRange object
‘Sheet1 contains 7 auto shapes, in this order: Rectangle 1, Rectangle 2, Oval 1, Rounded Rectange 1, Triangle 1, Oval 2, Triangle 2

Dim ws As Worksheet, shp As Shape

Set ws = Sheets(«Sheet1»)

‘———————————

‘refer Shapes collection ie. Shapes object

‘returns 7 (there are seven shapes in the collection)

MsgBox ws.Shapes.Count

‘———————————

‘refer each Shape object

For Each shp In ws.Shapes

‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)

shp.Placement = xlFreeFloating

Next

‘———————————

‘ShapeRange object

‘use the Range property to return multiple number of shapes — return a set of Shapes by specifying Name or Index Number — Shapes.Range(index)

‘using the Array function to construct an array of index numbers — set the fill forecolor for shapes one & four (Rectangle 1 & Rounded Rectange 1)

ws.Shapes.Range(Array(1, 4)).Fill.Solid

ws.Shapes.Range(Array(1, 4)).Fill.ForeColor.RGB = RGB(255, 0, 0)

‘using the Array function to construct an array of names — set the height for shapes named Rectangle 2 & Triangle 1 (shapes 2 & 5)

ws.Shapes.Range(Array(«Rectangle 2», «Triangle 1»)).Height = 20

‘for a single member of the collection, it is easier to use the Item method than using the Range property — set caption / text for the third shape (Oval 1)

ws.Shapes(3).TextFrame.Characters.Text = «Oval Shape«

‘activate sheet

ws.Activate

‘select shapes sixth & seventh (Oval 2, Triangle 2)

ActiveSheet.Shapes.Range(Array(6, 7)).Select

‘using the ShapeRange property of the Selection object to return all shapes in the selection

ActiveWindow.Selection.ShapeRange.Fill.Solid

ActiveWindow.Selection.ShapeRange.Fill.ForeColor.RGB = RGB(255, 255, 0)

‘return a single shape (seventh shape — Triangle 2) in the selection, by using Selection.ShapeRange(index), where index is the shape name or the index number

ActiveWindow.Selection.ShapeRange(2).TextFrame.Characters.Text = «Triangle«

End Sub

Example: for Form Controls, illustrating Shapes object, Shape object & ShapeRange object

Sub FormControls_ShapesObj_ShapeObj_ShapeRangeObj()
‘illustrating Form Controls — Shapes object, Shape object & ShapeRange object
‘Sheet1 contains 5 Form Controls, in this order: Button 1, Check Box 1, Option Button 1, Scroll Bar 1, Label 1

Dim ws As Worksheet, shp As Shape

Set ws = Sheets(«Sheet1»)

‘———————————

‘refer Shapes collection ie. Shapes object

‘returns 5 (there are seven shapes — Form Controls — in the collection)

MsgBox ws.Shapes.Count

‘———————————

‘refer each Shape object

For Each shp In ws.Shapes

‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)

shp.Placement = xlFreeFloating

Next

‘———————————

‘ShapeRange object

‘use the Range property to return multiple number of shapes — return a set of Shapes by specifying Name or Index Number — Shapes.Range(index)

‘using the Array function to construct an array of index numbers — set the Left property for shapes one & four (Button 1 & Scroll Bar 1)

ws.Shapes.Range(Array(1, 4)).Left = 25

‘using the Array function to construct an array of names — set the height for shapes named Check Box 1 & Option Button 1 (shapes 2 & 3)

ws.Shapes.Range(Array(«Check Box 1», «Option Button 1»)).Height = 20

‘for a single member of the collection, it is easier to use the Item method than using the Range property — set caption / text for the third shape (Option Button 1)

ws.Shapes(3).TextFrame.Characters.Text = «SelectOption«

‘activate sheet

ws.Activate

‘select shapes second & third (Check Box 1 & Option Button 1)

ActiveSheet.Shapes.Range(Array(2, 3)).Select

‘using the ShapeRange property of the Selection object to return all shapes in the selection — set a solid fill forecolor

ActiveWindow.Selection.ShapeRange.Fill.Solid

ActiveWindow.Selection.ShapeRange.Fill.ForeColor.RGB = RGB(255, 0, 0)

‘return a single shape (third shape — Option Button 1) in the selection, by using Selection.ShapeRange(index), where index is the shape name or the index number

‘set Option Button’s border line: as dash-dash-dot, thickness of 2 pts & color green

ActiveWindow.Selection.ShapeRange(2).Line.DashStyle = msoLineDashDotDot

ActiveWindow.Selection.ShapeRange(2).Line.Weight = 2

ActiveWindow.Selection.ShapeRange(2).Line.ForeColor.RGB = RGB(0, 255, 0)

End Sub

Example: for ActiveX Controls, illustrating Shapes object, Shape object & ShapeRange object

Sub ActiveXControls_OLEObjects_OLEObject_ShapeRangeObject()
‘illustrating ActiveX Controls — OLEObjects object, OLEObject object & ShapeRange object
‘Sheet1 contains 7 OLEObjects, in this order: ComboBox1, ListBox1, CommandButton1, OptionButton1, CheckBox1, SpinButton1, CommandButton2

Dim ws As Worksheet, obj As OLEObject

Set ws = Sheets(«Sheet1«)

‘Count the no. of OLEObjects in the OLEObjects collection — returns 7

MsgBox ws.OLEObjects.Count

‘refer each OLEObject object in worksheet

For Each obj In ws.OLEObjects

‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)

obj.Placement = xlFreeFloating

Next

‘Set the height of the OLEObject named CommandButton2

ws.OLEObjects(«CommandButton2»).Height = 30

‘———————————

‘ShapeRange object — OLE objects do not support many changes which can be made through ShapeRange

‘activate sheet

ws.Activate

‘select OLEObjects third & seventh (CommandButton1, CommandButton2)

ActiveSheet.OLEObjects(3).Select (True)

ActiveSheet.OLEObjects(7).Select (False)

‘using the ShapeRange property of the Selection object to return all OLEObjects in the selection — set shadow

ActiveWindow.Selection.ShapeRange.Shadow.Visible = True

‘using the ShapeRange property of the Selection object to return all OLEObjects in the selection — set height, in points

ActiveWindow.Selection.ShapeRange.Height = 20

‘return a single OLEObject (seventh OLEObject — CommandButton2) in the selection, by using Selection.ShapeRange(index), where index is the shape name or the index number

‘set the distance, in points, from the top edge of the object to the top of worksheet’s row 1

ActiveWindow.Selection.ShapeRange(2).Top = 270

End Sub

ActiveX Controls in VBA

By default, a control’s name (ie. code name) is based on its type ex. default name of a CommandButton is CommandButton1, second CommandButton will be CommandButton2, & so on. Every control name should be unique in a worksheet. An ActiveX control’s name is visible at the top of the Properties window (in the drop-down list where control is selected) where on the right is the control type (ex. CommandButton) and on its left is the name of the control (ex. CommandButton1). The control name (ie. CommandButton1) can be viewed & changed in the sheet’s Name box and also in the cell to the right of (Name) in the Properties window. You may also change the control name in code, using its Name property. Note that control name is different from its Caption, which is the text that may appear on the control.

ActiveX controls can be referred by name — the control name should be qualified with the sheet name when used from a module outside the sheet that contains the control. Control name is used to return the control from the Shapes or OLEObject collection ex. Sheets(«Sheet1»).OLEObjects(«CommandButton1»).Top = 25 or Sheets(«Sheet1»).Shapes(«CommandButton1»).Height = 20. Names of event procedures also correspond to the control’s name (ex. CommandButton1_Click).

ActiveX controls have associated event procedures which are triggered on clicking the control (you cannot assign any arbitrary macro to ActiveX controls like you do to Form controls). Event-handler procedures must be located in the code module of the object (viz. worksheet, UserForm) containing the control, or written in class modules. On top of the  code module, there are two drop-down boxes — selecting the control on the left will display the events on the right which are supported for that control. For example, a CommandButton control generates a Click event for which an event-handler sub procedure can be written as follows viz. clicking the CommandButton control (control name CommandButton1) will enter «Hello» in cell A1 of the sheet which contains the control & return this text in a message box:

Private Sub CommandButton1_Click()

Range(«A1»).Value = «Hello«

MsgBox Range(«A1»).Value

End Sub

Accessing ActiveX Control Properties in VBA 

Note: All illustrations below relate to the ActiveX control of CommandButton named «CommandButton1».

In VBA code, ActiveX controls can be referred by name & you may thus set the control properties, for example, to set the mouse pointer for CommandButton named «CommandButton1»:

Sheets(«Sheet1»).CommandButton1.MousePointer = fmMousePointerIBeam.

In Excel VBA, ActiveX controls are represented by OLEObject objects in the OLEObjects collection, so that ActiveX control properties can be set using the properties of an OLEObject object, for example:

Sheets(«Sheet1»).OLEObjects(«CommandButton1»).Top = 25 or Sheets(«Sheet1»).OLEObjects(«CommandButton1»).BottomRightCell.Interior.Color = RGB(255, 255, 0).

If the control property is listed in the Object Browser (in VBE, click View & then click Object Browser) under the class OLEObject, then you may use the OLEObject from the OLEObjects collection object, to set the property, otherwise (if the property is not listed under the OLEObject class in the Object Browser), then you must return the actual control object by using the Object property of the OLEObject object, for example to set the BackColor or the Caption property:

Sheets(«Sheet1»).OLEObjects(«CommandButton1»).Object.BackColor = RGB(255, 255, 0) or Sheets(«Sheet1»).OLEObjects(«CommandButton1»).Object.Caption = «Click to Run«.

Because an OLEObject object is also a member of the Shapes collection, many ActiveX control properties can be set using the properties of a Shape object, ex.

Dim sh As Shape
‘set sh to an existing CommandButton ActiveX control
Set shp = Sheets(«Sheet4»).Shapes(«CommandButton1»)
‘Type Property can be used only with the Shape object

If shp.Type = msoOLEControlObject Then

shp.Height = 26
shp.Placement = xlFreeFloating

shp.Locked = True

End If

Add an ActiveX Control, a Form Control or an AutoShape, in Worksheet

Add a new OLE object to an Excel sheet

Use the Add Method of the OLEObjects object, to add a new OLEObject to a sheet — this method returns an OLEObject representing the new OLE object. Syntax: OLEObjects.Add(ClassType, FileName, Link, DisplayAsIcon, IconFileName, IconIndex, IconLabel, Left, Top, Width, Height). All arguments are optional to specify. It is necessary to specify either the ClassType argument — which specifies the programmatic identifier (see below), as a string value, for the new object being added — or the FileName argument — which specifies the file name, as a string value, that is used to add the new object. Specifying the ClassType argument will ignore the FileName & Link arguments. Setting the Link argument to True will link the new object to the file whose FileName is specified whereas the False (default) setting will add the new object as a copy of the file without linking.

The new object will display as an icon or picture by setting the DisplayAsIcon argument to True, & in this case you can specify the icon by using the arguments of IconFileName & IconIndex. Only when the DisplayAsIcon argument is set to True, can you use the IconFileName argument to specify the file name containing the icon to be displayed & omitting this argument will display the default OLE class icon. Only when the DisplayAsIcon argument is set to True & the IconFileName argument specifies a valid file which contains icon(s), you can use the IconIndex argument to specify the number of the icon in the file & on non-existence of that index number the file’s first icon is used. Only when the DisplayAsIcon argument is set to True, can you use the IconLabel argument for specifying a string value to display a caption (or label) under the icon, & omitting this argument or setting it as an empty string («») will not display any caption.

The Left & Top arguments specify the distance of the new object, in points, from the left edge of column A or from the top of row 1 on a worksheet respectively (or the distance from the left edge / top edge of a chart). The Width & Height arguments specify the width & height of the new object, in points.

OLE programmatic identifier — also called a ProgID — is used to create an Automation object. The following is a list OLE programmatic identifiers for ActiveX controls:

OLE programmatic identifier
Below control is created By using the below ProgID
CheckBox Forms.CheckBox.1                          
ComboBox                          Forms.ComboBox.1
CommandButton Forms.CommandButton.1           
Frame Forms.Frame.1
Image Forms.Image.1
Label Forms.Label.1
ListBox Forms.ListBox.1
MultiPage Forms.MultiPage.1
OptionButton Forms.OptionButton.1
ScrollBar Forms.ScrollBar.1
SpinButton Forms.SpinButton.1
TabStrip Forms.TabStrip.1
TextBox Forms.TextBox.1
ToggleButton Forms.ToggleButton.1

Example: add an ActiveX control, check box to Sheet1 — return an OLEObject representing the new OLE object:

Dim objChBx As OLEObject
Set objChBx = Sheets(«Sheet1″).OLEObjects.Add(ClassType:=»Forms.CheckBox.1«, DisplayAsIcon:=False, Left:=20, Top:=20, Width:=100, Height:=20)
MsgBox objChBx.Name
‘TypeName Function returns the data-type about a variable — TypeName(varname)
‘returns CheckBox — Object Property of the OLEObject returns a OLE Automation object associated with this OLE object
MsgBox TypeName(objChBx.Object)

You may also use the AddOLEObject Method of the Shapes object  to add a new OLEObject to a sheet — this method returns a Shape object representing the new OLE object. Syntax: Shapes.AddOLEObject(ClassType, Filename, Link, DisplayAsIcon, IconFileName, IconIndex, IconLabel, Left, Top, Width, Height). All arguments are optional to specify & work similar to the Add Method of the OLEObjects object, as explained above.

Example: add an ActiveX control, check box to Sheet1 — return a Shape Object representing the new OLE object:

Dim shChkBx As Shape
Set shChkBx = Sheets(«Sheet1″).Shapes.AddOLEObject(ClassType:=»Forms.CheckBox.1«, DisplayAsIcon:=False, Left:=20, Top:=20, Width:=100, Height:=20)
MsgBox shChkBx.Name
‘Type Property can be used only with the Shape object
‘returns 12 — constant msoOLEControlObject indicating an OLE control object (ActiveX Control)
MsgBox shChkBx.Type 

Create a new Form Control

Use the Shapes.AddFormControl Method to create an Excel Form Control — this returns a Shape object representing the new control — Syntax: Shapes.AddFormControl(Type, Left, Top, Width, Height). All arguments are necessary to be specified. The Type argument specifies the type of the form control as per constants in the XlFormControl Enumeration. The Left & Top arguments specify the distance of the new object, in points, from the left edge of column A or from the top of row 1 on a worksheet respectively (or the distance from the left edge / top edge of a chart). The Width & Height arguments specify the width & height of the new object, in points.

Add a new AutoShape

Use the Shapes.AddShape Method to Add  a new AutoShape — this returns a Shape object that representing the new AutoShape — Syntax: Shapes.AddShape(Type, Left, Top, Width, Height). All arguments are necessary to specify. The Type argument specifies the shape type per the MsoAutoShapeType Enumeration. The Left argument specifies the distance of the left edge of the AutoShape’s bounding box, in points, from the left edge of the document. The Top argument specifies the distance of the top edge of the AutoShape’s bounding box, in points, from the top edge of the document. The Width & Height arguments specify the width & height of the AutoShape’s bounding box, in points.

MsoAutoShapeType Enumeration: msoShape16pointStar (value 94 — 16pointStar), msoShapeBalloon (value 137 — Balloon), msoShapeCube (value 14 — Cube), msoShapeDiamond (value 4 — Diamond), msoShapeDownArrow (value 36 — block arrow pointing down), msoShapeRightArrow (value 33 — block arrow pointing right), msoShapeLeftRightArrow (value 37 block arrow with arrowheads that point both left & right), msoShapeHeart (value 21 — Heart), msoShapeHexagon (value 10 — Hexagon), msoShapeIsoscelesTriangle (value 7 — IsoscelesTriangle), msoShapeOval (value 9 — Oval), msoShapeRectangle (value 1 — Rectangle), and so on.

To change the AutoShape type (other than a line, freeform drawing, or connector), set the AutoShapeType Property of the Shape object (Syntax: Shape.AutoShapeType) using the MsoAutoShapeType Enumeration. The shape will retain its size, color & other attributes on changing its type.

Illustrating Form Controls, ActiveX Controls & AutoShapes

Button (Form Control); Command Button (ActiveX Control)

A Button (Form Control)  or a Command Button (ActiveX Control) is typically used to execute a macro when clicked by a user. You can assign a macro to the Button (Form Control) but cannot assign a macro to ActiveX controls similar to Form controls. CommandButton (ActiveX control) can have associated event procedures which are triggered on clicking the control.

CommandButton (ActiveX control) can be used to control different events, so that you can write macros to execute the associated events. You can execute different actions specific to the option selected by the user to interact with the control: you may write a macro associated with the Click event of the CommandButton so that clicking on the CommandButton will run the code which is attached to the Click event or you can insert the name of a macro to be run on clicking the CommandButton; similarly you may write a separate macro associated with another event of the CommandButton which will be executed likewise. To write a macro associated with the Click event of the CommandButton — in VBE (Visual Basic Editor) select the name of the CommandButton (in the code module of the worksheet containing the control) from the top-left dropdown of the code window and then select Click from the top-right dropdown.

CommandButton (ActiveX control) offers more flexibility as compared to Button (Form control), having numerous properties which can be used to customize its functionality, appearance, fonts & other characteristics, as illustrated by separate examples of Button & CommandButton below:

Example: Use Shapes.AddFormControl Method to create an Excel Form Control (Button) — this returns a Shape object representing the new control — refer Image 2a

Sub FormControl_Button_Shape_Properties()
‘use Shapes.AddFormControl Method to create an Excel Form Control (Button) — this returns a Shape object representing the new control — refer Image 2a

Dim shpBtn As Shape, rng As Range

Set rng = Sheets(«Sheet1»).Range(«A2»)

‘Range.ColumnWidth Property returns or sets the width of all columns in the specified range, where one unit of column width is equal to the width of one character in the Normal style (width of the character zero is used for proportional fonts) — to return (does not set) the width of the range in points, use the Range.Width property

rng.ColumnWidth = 15

‘Range.RowHeight Property returns or sets the height of the first row in the range, in points — to set or return the total height of a range of cells in points, use the Height property.

rng.RowHeight = 20

‘for an already existing Form Control shape — Button, with the name «Button 1»

‘Set shpBtn = Sheets(«Sheet1»).Shapes(«Button 1»)

‘use Shapes.AddFormControl Method to create an Excel Form Control — this returns a Shape object representing the new control — Syntax: Shapes.AddFormControl(Type, Left, Top, Width, Height):

‘set object variable to the newly added Button Form control — position & size the Button with the cell assigned to the rng variable

Set shpBtn = Sheets(«Sheet1«).Shapes.AddFormControl(Type:=xlButtonControl, Left:=rng.Left, Top:=rng.Top, Width:=rng.Width, Height:=rng.Height)

With shpBtn

‘set the alternative text to a shape description when Shape object is saved to a Web page — alternative text may be displayed in the web browser in lieu of the shape’s image, or over the shape’s image when the mouse pointer hovers over the image (if browser supported).

.AlternativeText = «Click To Run«

‘set a String value as object’s name

.Name = «Button 1«

‘shape will not retain its original proportions when it is resized

.LockAspectRatio = msoFalse

‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)

.Placement = xlFreeFloating

‘use the Locked Property of the Shapes object to lock it — if not Locked (False), the object can be modified when the sheet is protected

.Locked = True

‘reset shape height & width

.Width = rng.Width

.Height = rng.Height

‘use the Shape.OnAction Property to assign a macro (ie. sets the macro name) to the shape — clicking on the shape will execute the NextStep macro

.OnAction = «NextStep«

‘TextFrame Property returns a TextFrame object which contains the alignment & anchoring properties for a shape — valid for only a shape having a text frame

‘this property is valid for Button (Form Control)
With .TextFrame

.HorizontalAlignment = xlHAlignCenter

.VerticalAlignment = xlVAlignDistributed

.Characters.Text = «ClickButton»

‘to set internal margins:

‘.AutoMargins = False

‘.MarginLeft = 0.25

‘.MarginRight = 0.1

‘.MarginTop = 0.2

‘.MarginBottom = 0.15

With .Characters(Start:=1, Length:=5).Font

.Name = «Arial«

.Bold = True

.ColorIndex = 3

.Size = 10

.Italic = True

End With

With .Characters(Start:=6, Length:=6).Font

.Name = «Calibiri«

.Bold = True

.Size = 10

.ColorIndex = 5

.Italic = False

.Underline = True

End With

End With

‘wrt to the cell which is under the upper-left corner of the object — set one cell below this

With .TopLeftCell.Offset(1, 0)

‘enter cell address in the cell

.Value = .Address

‘set cell color to green

.Interior.Color = RGB(0, 255, 0)

End With

End With

End Sub

Example: Add a new OLEObject to a sheet — ActiveX control (CommandButton) — set its properties by using the properties of an OLEObject object, & by using the Object property of the OLEObject object — refer Image 2b

Sub ActiveXControl_CommandButton_OLEobject_Properties()
‘add a new OLEObject to a sheet — ActiveX control (CommandButton) — set its properties by using the properties of an OLEObject object, & by using the Object property of the OLEObject object — refer Image 2b

‘OLEObject is not used for Form Controls

Dim objCmdBtn As OLEObject, shpBtn As Shape

Dim ws As Worksheet, rng As Range

Set ws = Sheets(«Sheet1«)

ws.Activate

Set rng = Range(«A2«)

‘delete ActiveX Control CommandButton objects

For Each objCmdBtn In ActiveSheet.OLEObjects

‘TypeName Function returns the data-type about a variable — TypeName(varname)

If TypeName(objCmdBtn.Object) = «CommandButton» Then objCmdBtn.Delete

Next objCmdBtn

‘delete Form Control Button objects

For Each shpBtn In ActiveSheet.Shapes

If shpBtn.Type = msoFormControl Then

If shpBtn.FormControlType = xlButtonControl Then shpBtn.Delete

End If

Next shpBtn

‘Range.ColumnWidth Property returns or sets the width of all columns in the specified range, where one unit of column width is equal to the width of one character in the Normal style (width of the character zero is used for proportional fonts) — to return (does not set) the width of the range in points, use the Range.Width property

rng.ColumnWidth = 15

‘Range.RowHeight Property returns or sets the height of the first row in the range, in points — to set or return the total height of a range of cells in points, use the Height property.

rng.RowHeight = 20

‘for an already existing ActiveX control, with the name «CommandButton1»

‘Set objCmdBtn = ws.OLEObjects(«CommandButton1»)

‘Use the Add Method of the OLEObjects object, to add a new OLEObject to a sheet — this method returns an OLEObject representing the new OLE object

‘set object variable to the newly added command button ActiveX control — position & size the CommandButton with the cell assigned to the rng variable

Set objCmdBtn = ws.OLEObjects.Add(ClassType:=»Forms.CommandButton.1«, DisplayAsIcon:=False, Left:=rng.Left, Top:=rng.Top, Width:=rng.Width, Height:=rng.Height)

With objCmdBtn

‘set a String value as object’s name

.Name = «CommandButton1»

‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)

.Placement = xlFreeFloating

‘use the Locked Property of the Shapes object to lock it — if not Locked (False), the object can be modified when the sheet is protected

.Locked = True

‘enable the object

.Enabled = True

‘returns the index number of the object within the collection of similar objects

MsgBox .Index

‘reset left & right distance of command button relative to the worksheet’s left & top edge

‘.Left = 50

‘.Top = 50

‘reset size of command button

‘.Height = 25

‘.Width = 35

‘set shadow

.Shadow = True

‘wrt to the cell which is under the upper-left corner of the object — set cell on its right

With .TopLeftCell.Offset(0, 1)

‘enter cell address in the cell

.Value = .Address

‘set cell color to green

.Interior.Color = RGB(0, 255, 0)

End With

‘Object Property of the OLEObject returns a OLE Automation object associated with the OLE object (objCmdBtn)

With .Object

.WordWrap = True

.MousePointer = fmMousePointerCross

‘load a picture into ActiveX control, using the LoadPicture Function — specify filename & address of image to be loaded

.Picture = LoadPicture(«C:UsersamitDocumentsPhotosDollar.jpg«)

.PicturePosition = fmPicturePositionAboveCenter

‘remove picture

.Picture = LoadPicture(«»)

.Caption = «Click«

‘set back color to yellow

.BackColor = RGB(255, 255, 0)

‘set font color to blue

.ForeColor = RGB(0, 0, 255)

‘for BackStyle, use fmBackStyleOpaque or fmBackStyleTransparent

.BackStyle = fmBackStyleOpaque

With .Font

.Name = «Arial«

.Bold = True

.Size = 10

.Italic = False

.Underline = False

End With

End With

End With

End Sub

Check Box — Form Control or ActiveX Control

With Check Box, user can select multiple options at a time on a worksheet or in a group box, by selecting each Check Box against which an option is available. CheckBox can be used in a singular manner viz. a single Check Box can be selected or deselected (by clicking itself) indicating whether an option is to be exercised or not. The Value property of a CheckBox indicates whether it is selected or not. A True value indicates that the CheckBox is selected, False indicates that it is cleared; and the Null value indicates that it is neither selected nor cleared, and the CheckBox will appear shaded in this case. The value of TripleState property should be set (can be set either in the Properties window or by using a macro or vba code) to True for the CheckBox to have a Null value. Option Buttons on the other hand are used in multiples viz. two or more, to indicate selection of mutually exculsive options — Option Button gets deselected only on selection of another Option Button and not by clicking itself.

Below we illustrate: (i) a Form Control Check Box & and assign it to a Macro; and (ii) an ActiveX Control CheckBox & a Macro associated with the Click event of this CheckBox.

Example: Form Control Check Box(es) & Macro to which they are assigned:

(1) Add a Form Control Check Box with the CheckBoxes.Add Method, set properties for the Form control (CheckBox) object — Refer Image 3a

Sub FormControl_CheckBox_Shape_Properties_1()
‘Add a Form Control Check Box with the CheckBoxes.Add Method, set properties for the Form control (CheckBox) object — Refer Image 3a

Dim shpChBx As Shape, ws As Worksheet, rng As Range, objChBx As OLEObject

Set ws = Sheets(«Sheet1»)

ws.Activate
‘————————

‘a quick way of adding multiple checkboxes (Form Control) in a worksheet & then deleting:

‘Dim cell As Range, rng As Range

‘Set rng = Range(«J5:J10»)

‘Set ws = Sheets(«Sheet4»)

‘ws.Activate

‘For Each cell In rng

‘With ws.CheckBoxes.Add(cell.Left, cell.Top, cell.Width, cell.Height)

‘.Characters.Text = cell.Address

‘End With

‘Next

‘ws.CheckBoxes.Delete

‘————————

Set rng = ws.Range(«B2»)

‘delete ActiveX Control CheckBox objects

For Each objChBx In ActiveSheet.OLEObjects

‘TypeName Function returns the data-type about a variable — TypeName(varname)

If TypeName(objChBx.Object) = «CheckBox» Then objChBx.Delete

Next objChBx

‘delete Form Control CheckBox objects

For Each shpChBx In ActiveSheet.Shapes

If shpChBx.Type = msoFormControl Then

If shpChBx.FormControlType = xlCheckBox Then shpChBx.Delete

End If

Next shpChBx

‘Range.ColumnWidth Property returns or sets the width of all columns in the specified range, where one unit of column width is equal to the width of one character in the Normal style (width of the character zero is used for proportional fonts) — to return (does not set) the width of the range in points, use the Range.Width property

rng.ColumnWidth = 10

‘Range.RowHeight Property returns or sets the height of the first row in the range, in points — to set or return the total height of a range of cells in points, use the Height property.

rng.RowHeight = 15

‘add a check box Form control — position & size the Check Box with the cell assigned to the rng variable

ws.CheckBoxes.Add(Left:=rng.Left, Top:=rng.Top, Width:=rng.Width, Height:=rng.Height).Select

With Selection

‘set a String value as object’s name

.Name = «Check Box 1«

‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)

.Placement = xlFreeFloating

‘use the Locked Property of the Shapes object to lock it — if not Locked (False), the object can be modified when the sheet is protected

.Locked = True

.Display3DShading = False

‘True (for Enabled Property) indicates that the control can be accessed through a vba code & respond to user-generated events (ie. the user can interact with the control by using mouse, keystrokes, accelerators, or hotkeys) — enable the object

.Enabled = True

‘check box will be printed when the document is printed

.PrintObject = True

.linkedCell = rng.Address

‘wrt to the cell which is under the upper-left corner of the checkbox — enter text in the same row to the right of the checkbox

.TopLeftCell.Offset(0, -1) = «Select Country«

‘Value property of a CheckBox indicates whether it is selected or not.

.Value = xlOn

‘.Value = xlOff

‘specify caption text

.Characters.Text = «USA«

‘alternatively:

‘.Caption = «USA«

‘use the Shape.OnAction Property to assign a macro (ie. sets the macro name) to the shape — clicking on the shape will execute the ChkBoxClick macro

.OnAction = «ChkBoxClick«

‘a ShapeRange object represents a subset of shapes on a document — it can contain a single shape, or a few shapes (viz. first, third & fifth shape out of a total of 8 shapes in a sheet), or it could represent all shapes in a document

With .ShapeRange

‘shape will retain its original proportions when it is resized

.LockAspectRatio = msoTrue

‘set the alternative text to a shape description when Shape object is saved to a Web page — alternative text may be displayed in the web browser in lieu of the shape’s image, or over the shape’s image when the mouse pointer hovers over the image (if browser supported).

.AlternativeText = «Click to Select«

‘set check box fill / interior

With .Fill

.Visible = msoTrue

.Solid

‘.ForeColor.SchemeColor = 13

.ForeColor.RGB = RGB(255, 255, 0)

.Transparency = 0

End With

‘set border for check box

With .Line

.Weight = 1

.DashStyle = msoLineSolid

.Style = msoLineSingle

.Transparency = 0

.Visible = msoTrue

‘.ForeColor.SchemeColor = 10

.ForeColor.RGB = RGB(255, 0, 0)

End With

End With

End With

‘—————————

‘copy check box and create new check box with same properties

‘set range size, for cell below the existing check box

rng.Offset(1, 0).ColumnWidth = rng.ColumnWidth

rng.Offset(1, 0).RowHeight = rng.Height

‘copy check box to clipboard

ws.Shapes(«Check Box 1»).Copy

‘paste a copy of the checkbox in the same sheet

ws.Paste

‘fit new check box in the cell below the existing check box

Selection.Left = rng.Offset(1, 0).Left

Selection.Top = rng.Offset(1, 0).Top

Selection.Name = «Check Box 2«

Selection.linkedCell = rng.Offset(1, 0).Address

Selection.Caption = «UK«

‘use the Shape.OnAction Property to assign a macro (ie. sets the macro name) to the shape — clicking on the shape will execute the ChkBoxClick macro

Selection.OnAction = «ChkBoxClick«

‘—————————

‘merge & format cells to the left of both check boxes

Union(rng.Offset(0, -1), rng.Offset(1, -1)).Select

With Selection

.HorizontalAlignment = xlCenter

.VerticalAlignment = xlCenter

.ReadingOrder = xlContext

.MergeCells = True

.WrapText = True

.Interior.Color = RGB(0, 255, 0)

.Borders.LineStyle = xlContinuous

.Borders.ColorIndex = 5

.Borders.Weight = xlMedium

End With

End Sub

(2) Use Shapes.AddFormControl Method to create an Excel Form Control (check box) — this returns a Shape object representing the new control — set properties for the Form control (CheckBox) object

Sub FormControl_CheckBox_Shape_Properties_2()
‘use Shapes.AddFormControl Method to create an Excel Form Control (check box) — this returns a Shape object representing the new control — set properties for the Form control (CheckBox) object — Refer Image 3a

Dim shpChBx As Shape, ws As Worksheet, rng As Range, objChBx As OLEObject

Set ws = Sheets(«Sheet1»)

ws.Activate

Set rng = ws.Range(«B2»)

‘delete ActiveX Control CheckBox objects

For Each objChBx In ActiveSheet.OLEObjects

‘TypeName Function returns the data-type about a variable — TypeName(varname)

If TypeName(objChBx.Object) = «CheckBox» Then objChBx.Delete

Next objChBx

‘delete Form Control CheckBox objects

For Each shpChBx In ActiveSheet.Shapes

If shpChBx.Type = msoFormControl Then

If shpChBx.FormControlType = xlCheckBox Then shpChBx.Delete

End If

Next shpChBx

‘Range.ColumnWidth Property returns or sets the width of all columns in the specified range, where one unit of column width is equal to the width of one character in the Normal style (width of the character zero is used for proportional fonts) — to return (does not set) the width of the range in points, use the Range.Width property

rng.ColumnWidth = 10

‘Range.RowHeight Property returns or sets the height of the first row in the range, in points — to set or return the total height of a range of cells in points, use the Height property.

rng.RowHeight = 15

‘for an already existing Form Control shape — Check Box, with the name «Check Box 1»

‘Set shpChBx = ws.Shapes(«Check Box 1»)

‘use Shapes.AddFormControl Method to create an Excel Form Control — this returns a Shape object representing the new control — Syntax: Shapes.AddFormControl(Type, Left, Top, Width, Height):

‘set object variable to the newly added check box Form control — position & size the Check Box with the cell assigned to the rng variable

Set shpChBx = ws.Shapes.AddFormControl(xlCheckBox, Left:=rng.Left, Top:=rng.Top, Width:=rng.Width, Height:=rng.Height)

With shpChBx

‘set a String value as object’s name

.Name = «Check Box 1«

‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)

.Placement = xlFreeFloating

‘use the Locked Property of the Shapes object to lock it — if not Locked (False), the object can be modified when the sheet is protected

.Locked = True

‘shape will retain its original proportions when it is resized

.LockAspectRatio = msoTrue

‘specify caption text

‘TextFrame Property returns a TextFrame object which contains the alignment & anchoring properties for a shape — valid for only a shape having a text frame

.TextFrame.Characters.Text = «USA«

‘set the alternative text to a shape description when Shape object is saved to a Web page — alternative text may be displayed in the web browser in lieu of the shape’s image, or over the shape’s image when the mouse pointer hovers over the image (if browser supported).

.AlternativeText = «Click to Select«

‘use the .OLEFormat.Object object to manipulate Display3DShading

.OLEFormat.Object.Display3DShading = False

‘use the Shape.OnAction Property to assign a macro (ie. sets the macro name) to the shape — clicking on the shape will execute the ChkBoxClick macro

.OnAction = «ChkBoxClick«

‘ControlFormat property of the Shape object returns a ControlFormat object that contains Microsoft Excel control properties — the ControlFormat property will fail if the shape is not a control.

With .ControlFormat

‘True  (for Enabled Property) indicates that the control can be accessed through a vba code & respond to user-generated events (ie. the user can interact with the control by using mouse, keystrokes, accelerators, or hotkeys).

‘enable the object

.Enabled = True

‘check box will be printed when the document is printed

.PrintObject = True

.linkedCell = rng.Address

‘Value property of a CheckBox indicates whether it is selected or not.

.Value = xlOn

‘.Value = xlOff

End With

‘set check box fill / interior

With .Fill

.Visible = msoTrue

.Solid

‘.ForeColor.SchemeColor = 13

.ForeColor.RGB = RGB(255, 255, 0)

.Transparency = 0

End With

‘set border for check box

With .Line

.Weight = 1

.DashStyle = msoLineSolid

.Style = msoLineSingle

.Transparency = 0

.Visible = msoTrue

‘.ForeColor.SchemeColor = 10

.ForeColor.RGB = RGB(255, 0, 0)

End With

End With

‘————————————-

‘copy check box and create new check box with same properties

‘set range size, for cell below the existing check box

rng.Offset(1, 0).ColumnWidth = rng.ColumnWidth

rng.Offset(1, 0).RowHeight = rng.Height

‘copy check box to clipboard

ws.Shapes(«Check Box 1»).Copy

‘paste a copy of the checkbox in the same sheet

ws.Paste

‘fit new check box in the cell below the existing check box

Selection.Left = rng.Offset(1, 0).Left

Selection.Top = rng.Offset(1, 0).Top

Selection.Name = «Check Box 2«

Selection.linkedCell = rng.Offset(1, 0).Address

Selection.Characters.Text = «UK«

‘alternatively

‘Selection.Caption = «UK«

‘use the Shape.OnAction Property to assign a macro (ie. sets the macro name) to the shape — clicking on the shape will execute the ChkBoxClick macro

Selection.OnAction = «ChkBoxClick«

‘enter text in the same row to the left of the checkbox

rng.Offset(0, -1) = «Select Country«

‘merge & format cells to the left of both check boxes

Union(rng.Offset(0, -1), rng.Offset(1, -1)).Select

With Selection

.HorizontalAlignment = xlCenter
.VerticalAlignment = xlCenter

.ReadingOrder = xlContext

.MergeCells = True

.WrapText = True

.Interior.Color = RGB(0, 255, 0)

.Borders.LineStyle = xlContinuous

.Borders.ColorIndex = 5

.Borders.Weight = xlMedium

End With

End Sub

Use with (1) or (2) above: Macro to which the Form Control Check Boxes are assigned — this procedure is located in a standard module of the workbook & executes on clicking the Form Control check boxes («Check Box 1» & «Check Box 2»)

Sub ChkBoxClick()

On Error Resume Next

Dim shpChBx1 As Shape, shpChBx2 As Shape, ws As Worksheet

Set ws = Sheets(«Sheet4»)

ws.Activate

Set shpChBx1 = ws.Shapes(«Check Box 1»)

Set shpChBx2 = ws.Shapes(«Check Box 2»)

If shpChBx1.ControlFormat.Value = xlOn Then

If shpChBx2.ControlFormat.Value = xlOff Then

Range(«$A$5:$B$13″).AutoFilter Field:=1, Criteria1:=»USA«

Else

Range(«$A$5:$B$13»).AutoFilter Field:=1

End If

Else

If shpChBx2.ControlFormat.Value = xlOff Then

Range(«$A$5:$B$13″).AutoFilter Field:=1, Criteria1:=»«

Else

Range(«$A$5:$B$13″).AutoFilter Field:=1, Criteria1:=»UK«

End If

End If

End Sub

Example: ActiveX Control CheckBox(es) & Macro associated with the Click event of the CheckBox:

Add a new OLEObject to a sheet — ActiveX control (CheckBox) — set its properties by using the properties of an OLEObject object, & by using the Object property of the OLEObject object — Refer Image 3b

Sub ActiveXControl_CheckBox_OLEobject_Properties()
‘add a new OLEObject to a sheet — ActiveX control (CheckBox) — set its properties by using the properties of an OLEObject object, & by using the Object property of the OLEObject object — Refer Image 3b

Dim ws As Worksheet, rng As Range

‘OLEObject is not used for Form Controls

Dim objChBx As OLEObject

Set ws = Sheets(«Sheet1»)

ws.Activate

Set rng = ws.Range(«B2»)

‘delete Form Control CheckBox objects in worksheet

ws.CheckBoxes.Delete

‘delete ActiveX Control CheckBox objects

For Each objChBx In ActiveSheet.OLEObjects

‘TypeName Function returns the data-type about a variable — TypeName(varname)

If TypeName(objChBx.Object) = «CheckBox» Then objChBx.Delete

Next objChBx

‘Range.ColumnWidth Property returns or sets the width of all columns in the specified range, where one unit of column width is equal to the width of one character in the Normal style (width of the character zero is used for proportional fonts) — to return (does not set) the width of the range in points, use the Range.Width property

rng.ColumnWidth = 10

‘Range.RowHeight Property returns or sets the height of the first row in the range, in points — to set or return the total height of a range of cells in points, use the Height property.

rng.RowHeight = 15

‘for an already existing ActiveX control checkbox, with the name «CheckBox1»

‘Set objChBx = ws.OLEObjects(«CheckBox1»)

‘set object variable to the newly added check box ActiveX control — position & size the CheckBox with the cell assigned to the rng variable

Set objChBx = ws.OLEObjects.Add(ClassType:=»Forms.CheckBox.1«, DisplayAsIcon:=False, Left:=rng.Left, Top:=rng.Top, Width:=rng.Width, Height:=rng.Height)

With objChBx

‘set a String value as object’s name

.Name = «CheckBox1«

‘returns the index number of the object within the collection of similar objects

MsgBox .Index

‘set shadow

.Shadow = True

‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)

.Placement = xlMove

‘use the Locked Property of the Shapes object to lock it — if not Locked (False), the object can be modified when the sheet is protected

.Locked = True

‘True (for Enabled property) indicates that the control can be accessed through a vba code & respond to user-generated events (ie. the user can interact with the control by using mouse, keystrokes, accelerators, or hotkeys) — enable the object

.Enabled = True

‘this property is ignored by ActiveX controls because these controls always load when a workbook is opened

.AutoLoad = True

‘check box will be printed when the document is printed

.PrintObject = True

‘ControlSource Property specifies a cell to set or store the Value property — changing the value of the control will automatically update the linked cell & a change in the linked cell will update the value of the control.

‘.LinkedCell = «Sheet1!B2«

.linkedCell = rng.Address

‘wrt to the cell which is under the upper-left corner of the checkbox — enter text in the same row to the right of the checkbox

.TopLeftCell.Offset(0, -1) = «Country«

‘if the property is not listed under the OLEObject class in the Object Browser, then you must return the actual control object by using the Object property of the OLEObject object

‘Object Property of the OLEObject returns a OLE Automation object associated with this OLE object

With .Object

.TextAlign = fmTextAlignCenter

‘will enable CheckBox to have three possible values, including the Null value, besides True & False

.TripleState = False

‘Value property of a CheckBox indicates whether it is selected or not. True (integer value 1) indicates that the CheckBox is selected, False (value of 0) indicates that it is cleared; and the Null value indicates that it is neither selected nor cleared, and the CheckBox will appear shaded in this case. The value of TripleState property should be set to True for the CheckBox to have a Null value.

.Value = True

‘determines how the control visually appears

.SpecialEffect = fmButtonEffectFlat

‘specify how caption will appear relative to the control

.Alignment = fmAlignmentLeft

‘Accelerator Property sets the key to access a control

.Accelerator = «h«

‘specify type of mouse pointer

.MousePointer = fmMousePointerArrow

‘load a picture into ActiveX control, using the LoadPicture Function — specify filename & address of image to be loaded

.Picture = LoadPicture(«C:UsersamitDocumentsPhotosDollar.jpg»)

‘alignment of the picture with its caption

.PicturePosition = fmPicturePositionAboveCenter

‘remove picture

.Picture = LoadPicture(«»)

‘specify caption text

.Caption = «USA«

‘caption text will wrap to the next line

.WordWrap = True

‘setting AutoSize to True automatically resizes the Caption while False (Default option) keeps the caption size constant wherein content exceeding the control area gets cut.

.AutoSize = False

‘set the background color for control to yellow

.BackColor = RGB(255, 255, 0)

‘set font color to red

.ForeColor = RGB(255, 0, 0)

‘set background to be Opaque or Transparent — BackStyle property should be set to fmBackStyleOpaque for the BackColor to have any effect

.BackStyle = fmBackStyleOpaque

With .Font

.Name = «Arial«

.Bold = True

.Size = 10

.Italic = False

.Underline = False

End With

End With

‘——————————

‘copy check box and create new check box with same properties

‘set range size, for cell below the existing check box

rng.Offset(1, 0).ColumnWidth = rng.ColumnWidth

rng.Offset(1, 0).RowHeight = rng.Height

‘copy check box to clipboard

.Copy

‘paste a copy of the checkbox in the same sheet

ws.Paste

‘fit new check box in the cell below the existing check box

Selection.Left = rng.Offset(1, 0).Left

Selection.Top = rng.Offset(1, 0).Top

Selection.Name = «CheckBox2«

ws.OLEObjects(«CheckBox2»).linkedCell = rng.Offset(1, 0).Address

ws.OLEObjects(«CheckBox2»).Object.Caption = «UK«

‘——————————

‘merge & format cells to the left of both check boxes

Union(rng.Offset(0, -1), rng.Offset(1, -1)).Select

With Selection

.HorizontalAlignment = xlCenter

.VerticalAlignment = xlCenter

.ReadingOrder = xlContext

.MergeCells = True

.Interior.Color = RGB(0, 255, 0)

End With

End With

End Sub

Macro associated with the Click event of the CheckBox1: this Event-handler procedure must be located in the code module of the object worksheet containing the control (CheckBox1)

Private Sub CheckBox1_Click()

On Error Resume Next

If CheckBox1.Object.Value = True Then

If CheckBox2.Object.Value = False Then

Range(«$A$5:$B$13″).AutoFilter Field:=1, Criteria1:=»USA«

Else

Range(«$A$5:$B$13»).AutoFilter Field:=1

End If

Else

If CheckBox2.Object.Value = False Then

Range(«$A$5:$B$13″).AutoFilter Field:=1, Criteria1:=»«

Else

Range(«$A$5:$B$13″).AutoFilter Field:=1, Criteria1:=»UK«

End If

End If

End Sub

Macro associated with the Click event of the CheckBox2: this Event-handler procedure must be located in the code module of the object worksheet containing the control (CheckBox2)

Private Sub CheckBox2_Click()

On Error Resume Next

If CheckBox2.Object.Value = True Then

If CheckBox1.Object.Value = False Then

Range(«$A$5:$B$13″).AutoFilter Field:=1, Criteria1:=»UK«

Else

Range(«$A$5:$B$13»).AutoFilter Field:=1

End If

Else

If CheckBox1.Object.Value = False Then

Range(«$A$5:$B$13″).AutoFilter Field:=1, Criteria1:=»«

Else

Range(«$A$5:$B$13″).AutoFilter Field:=1, Criteria1:=»USA«

End If

End If

End Sub

List Box & Combo Box — Form Control / ActiveX Control

A List Box or Combo Box is a list of items from which a user can select. They facilitate in accepting data from users and making entries in an Excel worksheet. List box may be of 3 types: (i) a single-selection list box which allows selection of a single item only; (ii) A multiple-selection list box which allows selection of one or more contiguous (adjacent) items; (iii) An extended-selection list box which allows selection of either a single item, or selection of multiple contiguous or noncontiguous items.

Difference between List Box and Combo Box:
1. The Combo Box is a drop-down list (the user-entered item or the list-selected item is visible in the text area, whereas list values are visible by using the drop-down), while a List Box shows a certain number of values with or without a scroll bar. In a Combo Box, only one row of items is visible at a given time (without using the drop-down) whereas in a List Box one or more can be visible at a time.
2. In a Combo Box you can select ony one option from the list, while in a List Box you can select multiple options from the list.
3. The user can enter his own item (in text area) in a ComboBox if it is not included in the list, which is not possible to do in a List Box. In this sense, Combo Box is a combination of Text Box and List Box.
4. Check Box can be used within List Box, but not within Combo Box. List Box allows you to display a check box next to each item in the list, to enable user to select items (this might be easier for the user than using the multiple selection methods).

Below we illustrate: (i) a Form Control List Box & and assign it to a Macro; and (ii) an ActiveX Control ListBox & a Macro associated with the Click event of this ListBox.

Example: Form Control List Box & Macro to which it is assigned:

Create an Excel Form Control (list box) & set ListBox properties — use Shapes.AddFormControl Method to create an Excel Form Control — this returns a Shape object representing the new control — Refer Image 4a

Sub FormControl_ListBox_Shape_Properties_1()
‘create an Excel Form Control (list box) & set ListBox properties — use Shapes.AddFormControl Method to create an Excel Form Control — this returns a Shape object representing the new control — Refer Image 4a
‘ControlFormat property of the Shape object returns a ControlFormat object that contains Microsoft Excel control properties — the ControlFormat property will fail if the shape is not a control.
‘Forms ListBox allows a single column, use an ActiveX ListBox for multi columns

Dim shpListBx As Shape, ws As Worksheet, rngListBx As Range, rngSource As Range, objListBx As OLEObject, i As Integer

Set ws = Sheets(«Sheet1»)

ws.Activate

‘set range/cell for ListBox

Set rngListBx = ws.Range(«A10»)

‘delete ActiveX Control ListBox objects

For Each objListBx In ActiveSheet.OLEObjects

‘TypeName Function returns the data-type about a variable — TypeName(varname)

If TypeName(objListBx.Object) = «ListBox» Then objListBx.Delete

Next objListBx

‘delete Form Control ListBox objects

For Each shpListBx In ActiveSheet.Shapes

If shpListBx.Type = msoFormControl Then

If shpListBx.FormControlType = xlListBox Then shpListBx.Delete

End If

Next shpListBx

Set rngSource = Range(«A3:A7»)

‘Range.ColumnWidth Property returns or sets the width of all columns in the specified range, where one unit of column width is equal to the width of one character in the Normal style (width of the character zero is used for proportional fonts) — to return (does not set) the width of the range in points, use the Range.Width property

rngListBx.ColumnWidth = 11

‘Range.RowHeight Property returns or sets the height of the first row in the range, in points — to set or return the total height of a range of cells in points, use the Height property.

rngListBx.RowHeight = 30

‘for an already existing Form Control shape — ListBox, with the name «List Box 1»

‘Set shpListBx = ws.Shapes(«List Box 1»)

‘set object variable to the newly added ListBox Form control — position & size the ListBox with the cell assigned to the rngListBx variable

‘use Shapes.AddFormControl Method to create an Excel Form Control — this returns a Shape object representing the new control — Syntax: Shapes.AddFormControl(Type, Left, Top, Width, Height):

Set shpListBx = ws.Shapes.AddFormControl(xlListBox, Left:=rngListBx.Left, Top:=rngListBx.Top, Width:=rngListBx.Width, Height:=rngListBx.Height)

‘to remove all items from listbox (not required for the newly created list box):

With shpListBx

‘remove all items if List Method has been used to set the text entries in the specified list box as an array of strings, or if the AddItem Method has been used to add items to a list box

If .ControlFormat.ListFillRange = «« Then

‘ControlFormat.ListCount Property determines the total number of items in a ListBox or ComboBox.

For i = .ControlFormat.ListCount To 1 Step -1

‘ControlFormat.RemoveItem Method removes one or more items from a list box or combo box — ControlFormat.RemoveItem(Index, Count) — Index is the number of the first item to be removed, having values from 1 to the number of items in the list — this method will fail if the list box has a defined fill range.

.ControlFormat.RemoveItem (i)

Next

Else

‘clear ListBox if filled with ListFillRange/RowSource (if ListFillRange property has been used to specify the source of a list)

.ControlFormat.ListFillRange = ««

End If

‘set a String value as object’s name

.Name = «List Box 1«

‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)

.Placement = xlFreeFloating

‘use the Locked Property of the Shapes object to lock it — if not Locked (False), the object can be modified when the sheet is protected

.Locked = True

‘shape will not retain its original proportions when it is resized

.LockAspectRatio = msoFalse

.AlternativeText = «LB«

‘turn 3D Shading Off

.OLEFormat.Object.Display3DShading = False

‘enable the object

.ControlFormat.Enabled = True

‘set ControlFormat.PrintObject Property to True where list box will be printed when the document is printed

.ControlFormat.PrintObject = True

‘ControlFormat.ListFillRange property specifies the source of a list (which could be a worksheet range in Excel), for a ComboBox or ListBox.

.ControlFormat.ListFillRange = rngSource.Address

‘alternatively:

‘.ControlFormat.ListFillRange = «$A$2:$A$7«

‘.ControlFormat.ListFillRange = Range(«A2:A7»).Address

‘.ControlFormat.ListFillRange = «NamedRange«

‘———————

‘ControlFormat.List Method returns or sets the text entries in the specified list box or a combo box, as an array of strings, or returns or sets a single text entry. An error occurs if there are no entries in the list — ControlFormat.List (Index)

‘fill ListBox

‘.OLEFormat.Object.List = rngSource.Value

‘.OLEFormat.Object.List = Range(«A2:A7»).Value

‘replace value of the second item in the list, after folling listbox using the ControlFormat.List Method:

‘.OLEFormat.Object.List(2) = «ChangeItem«

‘.OLEFormat.Object.List = Array(«2010», «2011», «2012», «2013»)

‘return first item:

MsgBox .ControlFormat.List(1)

‘alternatively — return first item:

MsgBox .OLEFormat.Object.List(1)

‘———————
‘ControlFormat.MultiSelect Property: Specifies whether multiple selections are allowed. There are 3 settings: (i) xlNone, the default setting, wherein only a single item can be selected; (ii) xlSimple which allows multiple selections wherein an item can be selected or deselected by clicking mouse or pressing SPACEBAR; and (iii) xlExtended which allows multiple selections, wherein by pressing SHIFT and simultaneously moving the up or down arrows (or pressing SHIFT and clicking mouse) continues selection from the previously selected item to the current selection (ie. a continuous selection) & this option also allows to select or deselect an item by pressing CTRL and clicking mouse.

.ControlFormat.MultiSelect = xlNone

‘ControlFormat.ListIndex Property returns or sets the index number of the currently selected item in a ComboBox or ListBox. This property cannot be used with multiselect list boxes.

.ControlFormat.ListIndex = 3

‘return selected item from ListBox ie. the value of list box — cannot be used with a multi-select ListBox

MsgBox .ControlFormat.List(.ControlFormat.ListIndex)

‘or:

‘return selected item(s) from ListBox — this can be used with a multi-select ListBox

‘ControlFormat.ListCount Property returns the total number of entries in a ListBox or ComboBox, & returns 0 (zero) for no entries in the list

For i = 1 To .ControlFormat.ListCount

‘Selected Property specifies whether an item is selected in a ListBox control (not valid for ComboBox). Syntax: Control.Selected(Item_Index).

If .OLEFormat.Object.Selected(i) Then

MsgBox .ControlFormat.List(i)

End If

Next i

‘Value Property: For the Form Controls ComboBox & ListBox (value cannot be used with a multi-select ListBox), value is the the index number of the currently selected item (ie. ControlFormat.ListIndex)

MsgBox .ControlFormat.Value

‘use the ControlFormat.LinkedCell property (not valid for a multi-select ListBox), to set the worksheet range linked to the index number of the currently selected item in a ComboBox or ListBox (ie. ControlFormat.ListIndex)

‘enter the selection’s list position to a specific cell

.ControlFormat.linkedCell = rngListBx.Address

‘to return the actual item from the input range, enter the index formula in the separate cell wherein you wish to get the actual item

rngListBx.Offset(-1, 0).Value = Application.WorksheetFunction.Index(rngSource, rngListBx.Value)

‘use the Shape.OnAction Property to assign a macro (ie. sets the macro name) to the shape — clicking on the shape will execute the ListBox_Change macro

.OnAction = «ListBox_Change»

End With

‘call the assigned macro

Call ListBox_Change

End Sub

Macro to which the Form Control ListBox is assigned — this procedure is located in a standard module of the workbook & executes on clicking / changing «List Box 1» value

Sub ListBox_Change()
‘this macro has been assigned to the «List Box 1» & will execute when the listbox value changes

Dim shpListBx As Shape, ws As Worksheet

Set ws = Sheets(«Sheet1»)

ws.Activate

‘set object variable to an existing Form Control shape — ListBox

Set shpListBx = ws.Shapes(«List Box 1»)

‘call the Sales_Region sub — argument / value is being supplied by this code to the Sales_Region procedure when it is called

‘when arguments are passed to a procedure from other procedures, then these are listed or declared between the parentheses viz. shpListBx.ControlFormat.Value

Call Sales_Region(shpListBx.ControlFormat.Value)

End Sub

This procedure is located in a standard module of the workbook & is called by the above macro (to which the Form Control ListBox is assigned)

Sub Sales_Region(i As Integer)
‘an external argument (Integer value) supplied by the calling sub (ListBox_Change) is used by this procedure to perform an action

If i = 1 Then

Call Sales_Total(«I»)

ElseIf i = 2 Then

Call Sales_Total(«G»)

ElseIf i = 3 Then

Call Sales_Total(«H»)

ElseIf i = 4 Then

Call Sales_Total(«E»)

ElseIf i = 5 Then

Call Sales_Total(«F»)

End If

    End Sub

This procedure is located in a standard module of the workbook & is called by the above macro

Sub Sales_Total(letter As String)
‘an external argument (String value) supplied by the calling sub (Sales_Region) is used by this procedure to perform an action

Dim shpListBx As Shape, ws As Worksheet, rng As Range, str As String

Set ws = Sheets(«Sheet1»)

Set shpListBx = ws.Shapes(«List Box 1»)

‘linked cell of listbox as a string value

str = shpListBx.ControlFormat.linkedCell

‘set range of linked cell

Set rng = ws.Range(str)

rng.Offset(2, 0).Value = ws.Range(«$» & letter & «$7»).Value

rng.Offset(2, 0).Interior.Color = RGB(0, 255, 0)

End Sub

Example: Create an Excel Form Control (list box) & set ListBox properties — use Shapes.AddFormControl Method to create an Excel Form Control — this returns a Shape object representing the new control

Sub FormControl_ListBox_Shape_Properties_2()
‘create an Excel Form Control (list box) & set ListBox properties — use Shapes.AddFormControl Method to create an Excel Form Control — this returns a Shape object representing the new control
‘Forms ListBox allows a single column, use an ActiveX ListBox for multi columns

Dim shpListBx As Shape, ws As Worksheet, rngListBx As Range, rngSource As Range, i As Integer

Set ws = Sheets(«Sheet1»)

ws.Activate

‘set range/cell for ListBox

Set rngListBx = ws.Range(«A10»)

‘delete all Form Control ListBox objects in worksheet:

ws.ListBoxes.Delete

Set rngSource = Range(«A3:A7»)

rngListBx.ColumnWidth = 11

rngListBx.RowHeight = 30

‘set object variable to the newly added ListBox Form control — position & size the ListBox with the cell assigned to the rngListBx variable

‘use Shapes.AddFormControl Method to create an Excel Form Control — this returns a Shape object representing the new control

Set shpListBx = ws.Shapes.AddFormControl(xlListBox, Left:=rngListBx.Left, Top:=rngListBx.Top, Width:=rngListBx.Width, Height:=rngListBx.Height)

‘remove all items from listbox (not required for the newly created list box):

With shpListBx

‘remove all items if List Method has been used to set the text entries in the specified list box as an array of strings, or if the AddItem Method has been used to add items to a list box

If .ControlFormat.ListFillRange = «« Then

‘ControlFormat.RemoveAllItems Method removes all entries from a Microsoft Excel list box or combo box.

.ControlFormat.RemoveAllItems

Else

‘clear ListBox if filled with ListFillRange/RowSource (if ListFillRange property has been used to specify the source of a list)

.ControlFormat.ListFillRange = ««

End If

‘set a String value as object’s name

.Name = «List Box 1«

‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)

.Placement = xlFreeFloating

‘use the Locked Property of the Shapes object to lock it — if not Locked (False), the object can be modified when the sheet is protected

.Locked = True

‘shape will not retain its original proportions when it is resized

.LockAspectRatio = msoFalse

.AlternativeText = «LB«

‘turn 3D Shading Off

.OLEFormat.Object.Display3DShading = False

‘enable the object

.ControlFormat.Enabled = True

‘set ControlFormat.PrintObject Property to True where list box will be printed when the document is printed

.ControlFormat.PrintObject = True

‘ControlFormat.AddItem Method adds an item to a list box or a combo box — ControlFormat.AddItem(Text, Index) — using this method clears any range specified by the ListFillRange property.

For i = 1 To rngSource.Rows.Count

‘Create a new row with AddItem

.ControlFormat.AddItem rngSource(i, 1).Value

Next i

‘alternatively:

‘With .ControlFormat

‘.AddItem «2010»

‘.AddItem «2011»

‘.AddItem «2012»

‘.AddItem «2013»

‘End With

‘xlSimple allows multiple selections

.ControlFormat.MultiSelect = xlSimple

‘Select multiple items in the ListBox

For i = 1 To .ControlFormat.ListCount

‘select every even item

If i Mod 2 = 0 Then

‘Selected Property specifies whether an item is selected in a ListBox control (not valid for ComboBox). Syntax: Control.Selected(Item_Index).

.OLEFormat.Object.Selected(i) = True

End If

Next i

End With

End Sub

Example: Create an Excel Form Control (list box) — add a new listbox using ListBoxes.Add method

Sub FormControl_ListBox_Properties_3()
‘create an Excel Form Control (list box) — add a new listbox using ListBoxes.Add method
‘Forms ListBox allows a single column, use an ActiveX ListBox for multi columns

Dim ws As Worksheet, rngListBx As Range, rngSource As Range, i As Integer

Set ws = Sheets(«Sheet1»)

ws.Activate

‘set range/cell for ListBox

Set rngListBx = ws.Range(«A10»)

‘delete all Form Control ListBox objects in worksheet:

ws.ListBoxes.Delete

Set rngSource = Range(«A3:A7»)

rngListBx.ColumnWidth = 11

rngListBx.RowHeight = 30

‘position & size the ListBox with the cell assigned to the rngListBx variable

‘add a new listbox — ListBoxes.Add:

ws.ListBoxes.Add(Left:=rngListBx.Left, Top:=rngListBx.Top, Width:=rngListBx.Width, Height:=rngListBx.Height).Select

With Selection

‘alternatively:

‘With ws.ListBoxes.Add(Left:=rngListBx.Left, Top:=rngListBx.Top, Width:=rngListBx.Width, Height:=rngListBx.Height)

‘remove all items if List Method has been used to set the text entries in the specified list box as an array of strings, or if the AddItem Method has been used to add items to a list box or a combo box (not required for the newly created list box)

If .ListFillRange = «« Then

‘RemoveAllItems Method removes all entries from a Microsoft Excel list box or combo box.

.RemoveAllItems

Else

‘clear ListBox if filled with ListFillRange/RowSource (if ListFillRange property has been used to specify the source of a list)

.ListFillRange = ««

End If

‘set a String value as object’s name

.Name = «List Box 1«

.Placement = xlFreeFloating

‘use the Locked Property to lock — if not Locked (False), the object can be modified when the sheet is protected

.Locked = True

‘turn 3D Shading Off

.Display3DShading = False

‘enable the object

.Enabled = True

‘set PrintObject Property to True where list box will be printed when the document is printed

.PrintObject = True

‘List Method returns or sets the text entries in the specified list box or a combo box, as an array of strings, or returns or sets a single text entry. An error occurs if there are no entries in the list — ControlFormat.List (Index)

‘fill ListBox

‘.List = rngSource.Value

‘AddItem Method adds an item to a list box or a combo box — AddItem(Text, Index) — using this method clears any range specified by the ListFillRange property.

For i = 1 To rngSource.Rows.Count

‘Create a new row with AddItem

.AddItem rngSource(i, 1).Value

Next i

‘alternatively, add item individually, ie. one by one:

‘.AddItem «2010»

‘.AddItem «2011»

‘.AddItem «2012»

‘.AddItem «2013»

‘xlSimple allows multiple selections

.MultiSelect = xlSimple

‘Select multiple items in the ListBox

For i = 1 To .ListCount

‘select every even item

If i Mod 2 = 0 Then

‘Selected Property specifies whether an item is selected in a ListBox control (not valid for ComboBox). Syntax: Control.Selected(Item_Index).

.Selected(i) = True

End If

Next i

End With

End Sub

Example: ActiveX Control ListBox & Macro associated with the Click event of the ListBox:

Add a new OLEObject to a sheet — ActiveX control (ListBox) — set its properties by using the properties of an OLEObject object, & by using the Object property of the OLEObject object — refer Image 4b

Sub ActiveXControl_ListBox_OLEobject_Properties_1()
‘add a new OLEObject to a sheet — ActiveX control (ListBox) — set its properties by using the properties of an OLEObject object, & by using the Object property of the OLEObject object — refer Image 4b

Dim ws As Worksheet, rngListBox As Range, rngSource As Range

‘OLEObject is not used for Form Controls

Dim objLB As OLEObject, i As Integer

Set ws = Sheets(«Sheet1»)

ws.Activate

‘set range/cell for ListBox

Set rngListBox = Range(«A8»)

‘delete ActiveX Control ListBox objects

For Each objLB In ActiveSheet.OLEObjects

‘TypeName Function returns the data-type about a variable — TypeName(varname)

If TypeName(objLB.Object) = «ListBox» Then objLB.Delete

Next objLB

‘delete all Form Control ListBox objects in worksheet:

ws.ListBoxes.Delete

Set rngSource = Range(«A2:D7»)

‘Range.ColumnWidth Property returns or sets the width of all columns in the specified range

rngSource.ColumnWidth = 6

‘Range.RowHeight Property returns or sets the height of the first row in the range, in points — to set or return the total height of a range of cells in points, use the Height property.

rngListBox.RowHeight = 50

‘ListBox range / cell (rngListBox) resized to add 2 columns

rngListBox.Resize(rngListBox.Rows.Count, rngListBox.Columns.Count + 2).MergeCells = True

‘for an already existing ActiveX control listbox, with the name «ListBox1»

‘Set objLB = ws.OLEObjects(«ListBox1»)

‘set object variable to the newly added listbox ActiveX control

Set objLB = ws.OLEObjects.Add(ClassType:=»Forms.ListBox.1«, DisplayAsIcon:=False, Left:=rngListBox.Left, Top:=rngListBox.Top, Width:=20, Height:=20)

With objLB

‘not required for a new listbox
If .ListFillRange = «« Then

‘Clear Method removes all items in a ComboBox or ListBox — it will not work if ComboBox or ListBox is bound to data, hence RowSource data should be cleared before use.

‘.Object.Clear

‘RemoveItem Method removes a specified row is removed from the list in a ComboBox or ListBox. Syntax: Control.RemoveItem(Row_Index). Row_Index specifies the row number to be removed, wherein the first row is numbered 0.

‘ListCount Property determines the total number of rows in a ListBox or ComboBox.

For i = .Object.ListCount — 1 To 0 Step -1

.Object.RemoveItem (i)

Next

Else

‘clear ListBox if filled with ListFillRange/RowSource

.ListFillRange = ««

End If

‘set a String value as name for the List Box

.Name = «ListBox1«

‘ListFillRange property specifies the source of a list (which could be a worksheet range in Excel), for a ComboBox or ListBox.

.ListFillRange = rngSource.Address

‘alternatively:

‘.ListFillRange = «$A$2:$D$7«

‘.ListFillRange = Range(«A2:D7»).Address

‘.ListFillRange = «NamedRange«

‘LinkedCell property sets the worksheet range linked to the control’s value so that the linked cell displays the selected value from the ListBox control — you cannot link a worksheet cell for MultiSelect ListBox by using the LinkedCell property

‘LinkedCell is to the right of the ListBox cell

With rngListBox.Offset(0, 1)

.Value = ««

.Interior.Color = vbYellow

.HorizontalAlignment = xlCenter

End With

.linkedCell = rngListBox.Offset(0, 1).Address

‘Object Property of the OLEObject returns a OLE Automation object associated with this OLE object

With .Object

‘determines how the control visually appears

‘.SpecialEffect = fmSpecialEffectRaised

‘ColumnHeads Property: A Boolean value (True/False) which determines display of column headings (in a single row) for ComboBox or ListBox.

.ColumnHeads = True

‘ColumnCount Property specifies the number of columns to be displayed in a ComboBox or ListBox. A ColumnCount value of 0 does not display any column and a setting of -1 displays all columns.

.ColumnCount = 4

‘set width of each column — displays only the first column

.ColumnWidths = «70;0;0;0«

.BorderStyle = fmBorderStyleSingle

.BorderColor = RGB(255, 0, 0)

.MatchEntry = fmMatchEntryFirstLetter

.ListStyle = fmListStyleOption

‘set background color

.BackColor = RGB(216, 216, 216)

‘set font color to red

.ForeColor = RGB(0, 0, 255)

With .Font

.Name = «Arial«

.Bold = False

.Size = 9

.Italic = False

.Underline = False

End With

‘MultiSelect Property: Specifies whether multiple selections are allowed. There are 3 settings: (i) fmMultiSelectSingle (value 0), the default setting, wherein only a single item can be selected; (ii) fmMultiSelectMulti (value 1) which allows multiple selections wherein an item can be selected or deselected by clicking mouse or pressing SPACEBAR; and (iii) fmMultiSelectExtended (value 2) which allows multiple selections, wherein by pressing SHIFT and simultaneously moving the up or down arrows (or pressing SHIFT and clicking mouse) continues selection from the previously selected item to the current selection (ie. a continuous selection) & this option also allows to select or deselect an item by pressing CTRL and clicking mouse.

.MultiSelect = fmMultiSelectSingle

‘ListIndex Property determines which item is selected in a ComboBox or ListBox. The first item in a list has a ListIndex value of 0, the second item has a value of 1, and so on.

.ListIndex = 1

‘ListCount Property determines the total number of rows in a ListBox or ComboBox.

‘MsgBox .ListCount

‘TextColumn property enables display of one set of values to the user but store a different set of values (per column specified in the BoundColumn property).

‘TextColumn property specifies the column of data in a ListBox that supplies data for its Text property — the TextColumn property determines the column whose value the Text property will return whereas the BoundColumn property determines the column whose value the Value property returns. The Text property returns the same as Value if the TextColumn property is not set. Setting the TextColumn value to -1 indicates that the first column with a ColumnWidths value greater than 0 will be displayed. Setting the TextColumn value to 0 returns the ListIndex value (the number of the selected row) in Text Property — this setting is useful if you want to determine the row of the selected item.

.TextColumn = 1

‘BoundColumn Property: Specifies the column from which value is to be stored in a multicolumn ComboBox or ListBox, when a row is selected by the user. First column has a BoundColumn value of 1

‘Setting the BoundColumn value to 0 assigns the value of the ListIndex property (which is the number of the selected row) as the value of the control (ComboBox or ListBox).

.BoundColumn = 4

‘Value Property: For the controls ComboBox and ListBox (value cannot be used with a multi-select ListBox), it is the value in the BoundColumn of the currently selected row (BoundColumn property specifies the column from which value is to be stored in a multicolumn ComboBox or ListBox, when a row is selected by the user).

MsgBox .Value

End With

‘size the ListBox with the resized range

‘the Range.Width property returns the width of a column in points

.Width = rngListBox.Resize(rngListBox.Rows.Count, rngListBox.Columns.Count + 2).Width

.Height = rngListBox.Height

‘set shadow

.Shadow = False

‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)

.Placement = xlFreeFloating

‘use the Locked Property of the Shapes object to lock it — if not Locked (False), the object can be modified when the sheet is protected

.Locked = True

‘enable the object

.Enabled = True

‘list box will be printed when the document is printed

.PrintObject = True

.Activate

End With

End Sub

Macro associated with the Click event of the ListBox1: this Event-handler procedure must be located in the code module of the object worksheet containing the control (ListBox1)

Private Sub ListBox1_Click()
‘on clicking / selecting an item in the ActiveX Control ListBox1

On Error Resume Next

Dim cat As String, str As String, rng As Range, BMI As Single

Set rng = Range(«A10»)

rng.Resize(rng.Rows.Count, rng.Columns.Count + 2).MergeCells = True

‘Body Mass Index formula is — weight in kilograms divided by the square of height in meters: kg/m2

‘BMI Categories:

‘Underweight = <18.5

‘Normal weight = 18.5–24.9

‘Overweight = 25–29.9

‘Obesity = BMI of 30 or greater

‘assign Value property to BMI

BMI = ListBox1.Object.Value

If BMI < 18.5 Then

cat = «Underweight«

ElseIf BMI < 25 Then

cat = «Normal Weight«

ElseIf BMI < 30 Then

cat = «Overweight«

ElseIf BMI >= 30 Then

cat = «Obese«

End If

With rng

.Interior.Color = vbGreen

.HorizontalAlignment = xlCenter

‘Listbox Text Property gives the Name, & BMI Category (cat) is derived from BMI (Listbox Value Property)

.Value = ListBox1.Object.Text & » is » & cat

End With

End Sub

Example: Add a new OLEObject to a sheet — ActiveX control (ListBox) — set its properties by using the properties of an OLEObject object, & by using the Object property of the OLEObject object — refer Image 4c

Sub ActiveXControl_ListBox_OLEobject_Properties_2()
‘add a new OLEObject to a sheet — ActiveX control (ListBox) — set its properties by using the properties of an OLEObject object, & by using the Object property of the OLEObject object — refer Image 4c

Dim ws As Worksheet, rngListBox As Range, rngSource As Range

‘OLEObject is not used for Form Controls

Dim objLB As OLEObject, i As Integer

Set ws = Sheets(«Sheet9»)

ws.Activate

‘set range/cell for ListBox

Set rngListBox = Range(«A8»)

‘delete ActiveX Control ListBox objects

For Each objLB In ActiveSheet.OLEObjects

‘TypeName Function returns the data-type about a variable — TypeName(varname)

If TypeName(objLB.Object) = «ListBox» Then objLB.Delete

Next objLB

‘delete Form Control ListBox objects

Dim sh As Shape

For Each sh In ActiveSheet.Shapes

If sh.Type = msoFormControl Then

If sh.FormControlType = xlListBox Then sh.Delete

End If

Next sh

Set rngSource = Range(«A2:C7»)

‘ListBox range / cell (rngListBox) resized to add 2 columns

rngListBox.Resize(rngListBox.Rows.Count, rngListBox.Columns.Count + 2).MergeCells = True

‘Range.ColumnWidth Property returns or sets the width of all columns in the specified range

rngListBox.Resize(1, rngListBox.Columns.Count + 2).ColumnWidth = 9

‘Range.RowHeight Property returns or sets the height of the first row in the range, in points — to set or return the total height of a range of cells in points, use the Height property.

rngListBox.RowHeight = 40

‘for an already existing ActiveX control listbox, with the name «ListBox1»

‘Set objLB = ws.OLEObjects(«ListBox1»)

‘set object variable to the newly added listbox ActiveX control

Set objLB = ws.OLEObjects.Add(ClassType:=»Forms.ListBox.1«, DisplayAsIcon:=False, Left:=rngListBox.Left, Top:=rngListBox.Top, Width:=100, Height:=20)

With objLB

‘not required for a new listbox

If .ListFillRange = «» Then

‘.Object.Clear

‘deleting row from ListBox using RemoveItem method:

For i = .Object.ListCount — 1 To 0 Step -1

.Object.RemoveItem (i)

Next

Else

‘clear ListBox if filled with ListFillRange/RowSource

.ListFillRange = ««

End If

‘set a String value as name for the List Box

.Name = «ListBox1«

‘remove LinkedCell — you cannot link a worksheet cell for MultiSelect ListBox by using the LinkedCell property

.linkedCell = ««

‘Object Property of the OLEObject returns a OLE Automation object associated with this OLE object

With .Object

‘do not display column headings

.ColumnHeads = False

‘ColumnCount Property specifies the number of columns to be displayed in a ComboBox or ListBox. A ColumnCount value of 0 does not display any column and a setting of -1 displays all columns.

.ColumnCount = 3

‘set width of each column

.ColumnWidths = «50;40;40«

‘allow multiple selections in ListBox

.MultiSelect = fmMultiSelectMulti

.BorderStyle = fmBorderStyleSingle

.BorderColor = RGB(255, 0, 0)

.MatchEntry = fmMatchEntryFirstLetter

.ListStyle = fmListStyleOption

‘set background color

.BackColor = RGB(216, 216, 216)

‘set font color to red

.ForeColor = RGB(0, 0, 255)

With .Font

.Name = «Arial«

.Bold = False

.Size = 9

.Italic = False

.Underline = False

End With

‘AddItem Method adds an item to the list (in a single-column ListBox or ComboBox) & adds a row to the list or an item for each row (in a multi-column ListBox or ComboBox). Syntax: Control.AddItem(Item, Index). Item specifies the item or row to add. Index specifies the position where the new item or row is placed within the list, and if omitted, the item or row is added at the end. The item or row numbers begin with zero, and the first item or row is numbered 0, and so on. The value of Index cannot be greater than the total number of rows (ie. value of ListCount property). AddItem method will not work if ComboBox or ListBox is bound to data, hence RowSource data should be cleared before use.

Dim iRow As Integer, iColumn As Integer

For iRow = 1 To rngSource.Rows.Count

‘Create a new row with AddItem

.AddItem rngSource(iRow, 1).Value

For iColumn = 2 To rngSource.Columns.Count

‘add item in columns of each row, using List property

.List(iRow — 1, iColumn — 1) = rngSource(iRow, iColumn).Value

Next iColumn

Next iRow

‘In a Multiple Selection enabled ListBox, ListIndex returns the index of the row that has focus, irrespective of whether that row is selected or not. Hence the Selected property of the ListBox (and not the ListIndex property) shoud be used here to return and set a selection.

‘Select items in the ListBox

For i = 1 To .ListCount

‘select every even item

If i Mod 2 = 0 Then

‘Selected Property specifies whether an item is selected in a ListBox control (not valid for ComboBox). Syntax: Control.Selected(Item_Index).

.Selected(i — 1) = True

End If

Next i

‘copying Selected rows in a multi-column ListBox to corresponding worksheet rows & columns, below the ListBox:

Dim counter As Integer

counter = 0

For i = 0 To .ListCount — 1

If .Selected(i) = True Then

counter = counter + 1

For iColCount = 1 To .ColumnCount

ws.Cells(rngListBox.Row + counter, iColCount).Value = .List(i, iColCount — 1)

‘alternatively, use Column Property instead of List property

‘Column Property refers to a specific column, or column and row combination, in a multiple-column ComboBox or ListBox. Syntax: Control.Column(iColumn, iRow).iColumn specifies the column number & iRow specifies the row number wherein both column & row nos start with zero for the first column & row. Specifying both column and row numbers will refer to a specific item, and specifying only the column number will refer to a specific column in the current row viz. ListBox1.Column(1) refers the second column.

‘ws.Cells(rngListBox.Row + counter, iColCount).Value = .Column(iColCount — 1, i)

Next iColCount

End If

Next i

End With

‘size the ListBox with the resized range

‘the Range.Width property returns the width of a column in points

.Width = rngListBox.Resize(rngListBox.Rows.Count, rngListBox.Columns.Count + 2).Width

‘Range.Height Property returns or sets the height of the range, in points

.Height = rngListBox.Height

‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)

.Placement = xlFreeFloating

‘use the Locked Property of the Shapes object to lock it — if not Locked (False), the object can be modified when the sheet is protected

.Locked = True

‘enable the object

.Enabled = True

.Activate

End With

End Sub

Example: Form Control Combo Box & Macro to which it is assigned:

Create an Excel Form Control (combo box) & set ComboBox properties — use Shapes.AddFormControl Method to create an Excel Form Control — this returns a Shape object representing the new control — Refer Image 5a

Sub FormControl_ComboBox_Shape_Properties()
‘create an Excel Form Control (combo box) — use Shapes.AddFormControl Method to create an Excel Form Control — this returns a Shape object representing the new control — refer Image 5a
‘ControlFormat property of the Shape object returns a ControlFormat object that contains Microsoft Excel control properties — the ControlFormat property will fail if the shape is not a control.
‘Form Control ComboBox allows a single column, use an ActiveX ComboBox for multi columns
‘use an ActiveX ComboBox to enable the user to edit the text in the text box — Form Control ComboBox does not allow this

Dim shpComboBx As Shape, ws As Worksheet, rngComboBx As Range, rngSource As Range, objComboBx As OLEObject, i As Integer

Set ws = Sheets(«Sheet1»)

ws.Activate

‘set range/cell for ComboBox

Set rngComboBx = ws.Range(«B10»)

‘delete ActiveX Control ComboBox objects

For Each objComboBx In ActiveSheet.OLEObjects

‘TypeName Function returns the data-type about a variable — TypeName(varname)

If TypeName(objComboBx.Object) = «ComboBox» Then objComboBx.Delete

Next objComboBx

‘delete Form Control ComboBox objects

For Each shpComboBx In ActiveSheet.Shapes

If shpComboBx.Type = msoFormControl Then

If shpComboBx.FormControlType = xlDropDown Then shpComboBx.Delete

End If

Next shpComboBx

Set rngSource = Range(«B2:F2»)

‘Range.ColumnWidth Property returns or sets the width of all columns in the specified range, where one unit of column width is equal to the width of one character in the Normal style (width of the character zero is used for proportional fonts) — to return (does not set) the width of the range in points, use the Range.Width property

rngComboBx.ColumnWidth = 11

‘Range.RowHeight Property returns or sets the height of the first row in the range, in points — to set or return the total height of a range of cells in points, use the Height property.

rngComboBx.RowHeight = 17

‘for an already existing Form Control shape — ComboBox, with the name «Combo Box 1»

‘Set shpComboBx = ws.Shapes(«Combo Box 1»)

‘set object variable to the newly added ComboBox Form control — position & size the ComboBox with the cell assigned to the rngComboBx variable

‘use Shapes.AddFormControl Method to create an Excel Form Control — this returns a Shape object representing the new control — Syntax: Shapes.AddFormControl(Type, Left, Top, Width, Height):

Set shpComboBx = ws.Shapes.AddFormControl(xlDropDown, Left:=rngComboBx.Left, Top:=rngComboBx.Top, Width:=rngComboBx.Width, Height:=rngComboBx.Height)

‘remove all items from ComboBox:

With shpComboBx

‘remove all items if List Method has been used to set the text entries in the specified list box as an array of strings, or if the AddItem Method has been used to add items to a list box

If .ControlFormat.ListFillRange = «« Then

‘ControlFormat.RemoveAllItems Method removes all entries from a Microsoft Excel list box or combo box.

‘.ControlFormat.RemoveAllItems

‘ControlFormat.ListCount Property determines the total number of items in a ListBox or ComboBox.

For i = .ControlFormat.ListCount To 1 Step -1

‘ControlFormat.RemoveItem Method removes one or more items from a list box or combo box — ControlFormat.RemoveItem(Index, Count) — Index is the number of the first item to be removed, having values from 1 to the number of items in the list — this method will fail if the list box has a defined fill range.

.ControlFormat.RemoveItem (i)

Next

Else

‘clear ComboBox if filled with ListFillRange/RowSource (if ListFillRange property has been used to specify the source of a list)

.ControlFormat.ListFillRange = ««

End If

‘set a String value as object’s name

.Name = «Combo Box 1«

‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)

.Placement = xlFreeFloating

‘use the Locked Property of the Shapes object to lock it — if not Locked (False), the object can be modified when the sheet is protected

.Locked = True

‘shape will retain its original proportions when it is resized

.LockAspectRatio = msoTrue

.AlternativeText = «ComBx«

‘turn 3D Shading Off

.OLEFormat.Object.Display3DShading = True

‘enable the object

.ControlFormat.Enabled = True

‘set ControlFormat.PrintObject Property to True where list box will be printed when the document is printed

.ControlFormat.PrintObject = True

‘ControlFormat.ListFillRange property specifies the source of a list (which could be a worksheet range in Excel), for a ComboBox or ListBox.

.ControlFormat.ListFillRange = rngSource.Address

‘alternatively:

‘.ControlFormat.ListFillRange = «$B$2:$F$2»

‘.ControlFormat.ListFillRange = Range(«B2:F2»).Address

‘.ControlFormat.ListFillRange = «NamedRange»

‘———————

‘ControlFormat.List Method returns or sets the text entries in the specified list box or a combo box, as an array of strings, or returns or sets a single text entry. An error occurs if there are no entries in the list — ControlFormat.List(Index)

‘fill ComboBox

‘.OLEFormat.Object.List = rngSource.Value

‘.OLEFormat.Object.List = Range(«B2:F2»).Value

‘replace value of the second item in the list, using the ControlFormat.List Method:

‘.OLEFormat.Object.List(2) = «ChangeItem»

‘.OLEFormat.Object.List = Array(«2010», «2011», «2012», «2013»)

‘return first item:

MsgBox .ControlFormat.List(1)

‘alternatively — return first item:

MsgBox .OLEFormat.Object.List(1)

‘ControlFormat.DropDownLines Property returns or sets the number of list lines displayed in the drop-down portion of a combo box. ControlFormat.DropDownLines

.ControlFormat.DropDownLines = 3

‘ControlFormat.AddItem Method adds an item to a list box or a combo box — ControlFormat.AddItem(Text, Index) — using this method clears any range specified by the ListFillRange property.

For i = 1 To rngSource.Columns.Count

‘Create a new row with AddItem

.ControlFormat.AddItem rngSource(1, i).Value

Next i

‘alternatively:

‘With .ControlFormat

‘.AddItem «2010»

‘.AddItem «2011»

‘.AddItem «2012»

‘.AddItem «2013»

‘End With

‘ControlFormat.ListIndex Property returns or sets the index number of the currently selected item in a ComboBox or ListBox. This property cannot be used with multiselect list boxes.

‘ComboBox displays the current value in the text box, regardless of how that value is entered

.ControlFormat.ListIndex = 1

‘return selected item from ComboBox

MsgBox .ControlFormat.List(.ControlFormat.ListIndex)

‘ControlFormat.ListCount Property returns the total number of entries in a ListBox or ComboBox, & returns 0 (zero) for no entries in the list

MsgBox .ControlFormat.ListCount

‘Value Property: For the Form Controls ComboBox & ListBox (value cannot be used with a multi-select ListBox), value is the the index number of the currently selected item (ie. ControlFormat.ListIndex)

MsgBox .ControlFormat.Value

‘use the ControlFormat.LinkedCell property (not valid for a multi-select ComboBox), to set the worksheet range linked to the index number of the currently selected item in a ComboBox or ListBox (ie. ControlFormat.ListIndex)

‘enter the selection’s list position to a specific cell — the linked cell returns the number of the selected item in the drop-down list of the combo box.

.ControlFormat.linkedCell = rngComboBx.Address

‘to return the actual item from the input range, enter the index formula in the separate cell wherein you wish to get the actual item

‘rngComboBx.Offset(-1, 0).Value = Application.WorksheetFunction.Index(rngSource, rngComboBx.Value)

‘use the Shape.OnAction Property to assign a macro (ie. sets the macro name) to the shape — clicking on the shape will execute the ComboBoxClick macro

.OnAction = «ComboBoxClick«

End With

‘————————————-

‘copy combo box and create new combo box with same properties

‘set range size, for cell below the existing combo box

rngComboBx.Offset(1, 0).ColumnWidth = rngComboBx.ColumnWidth

rngComboBx.Offset(1, 0).RowHeight = rngComboBx.Height

‘copy combo box to clipboard

ws.Shapes(«Combo Box 1»).Copy

‘paste a copy of the combobox in the same sheet

ws.Paste

‘fit new combo box in the cell below the existing check box

Selection.Left = rngComboBx.Offset(1, 0).Left

Selection.Top = rngComboBx.Offset(1, 0).Top

Selection.Name = «Combo Box 2«

Selection.linkedCell = rngComboBx.Offset(1, 0).Address

‘use the Shape.OnAction Property to assign a macro (ie. sets the macro name) to the shape — clicking on the shape will execute the ComboBoxClick macro

Selection.OnAction = «ComboBoxClick«

Dim rngSource2 As Range

Set rngSource2 = Range(«A3:A7»)

ws.Shapes(«Combo Box 2»).OLEFormat.Object.List = rngSource2.Value

‘————————————-

‘call the ComboBoxClick macro

Call ComboBoxClick

End Sub

Macro to which the Form Control ComboBox is assigned — this procedure is located in a standard module of the workbook & executes on clicking / changing «Combo Box 1» or «Combo Box 2» value

Sub ComboBoxClick()
‘this macro has been assigned to «Combo Box 1» & «Combo Box 2», & will execute when combobox selection changes

Dim shpComboBx1 As Shape, shpComboBx2 As Shape, ws As Worksheet, rngSource As Range, rngResult As Range, c As Integer, r As Integer

Set ws = Sheets(«Sheet1»)

ws.Activate

Set rngSource = Range(«B3:F7»)

Set rngResult = Range(«B13»)

‘set object variable to an existing Form Control shape — ComboBox

Set shpComboBx1 = ws.Shapes(«Combo Box 1»)

Set shpComboBx2 = ws.Shapes(«Combo Box 2»)

‘column number in range given by combo box 1

c = shpComboBx1.ControlFormat.Value

‘row number in range given by combo box 2

r = shpComboBx2.ControlFormat.Value

rngResult.Value = Application.WorksheetFunction.Index(rngSource, r, c)

rngResult.Interior.Color = RGB(0, 255, 0)

rngResult.NumberFormat = «$#,##0«

End Sub

Example: ActiveX Control ComboBox & Macro associated with the Click event of the ComboBox:

Add a new OLEObject to a sheet — ActiveX control (ComboBox) — set its properties by using the properties of an OLEObject object, & by using the Object property of the OLEObject object — refer Image 5b

Sub ActiveXControl_ComboBox_OLEobject_Properties()
‘add a new OLEObject to a sheet — ActiveX control (ComboBox) — set its properties by using the properties of an OLEObject object, & by using the Object property of the OLEObject object — refer Image 5b

Dim ws As Worksheet, rngComboBox As Range, rngSource As Range

‘OLEObject is not used for Form Controls

Dim objCoBx As OLEObject, i As Integer

Set ws = Sheets(«Sheet1»)

ws.Activate

‘set range/cell for ComboBox

Set rngComboBox = Range(«A8»)

‘delete ActiveX Control ComboBox objects

For Each objCoBx In ActiveSheet.OLEObjects

‘TypeName Function returns the data-type about a variable — TypeName(varname)

If TypeName(objCoBx.Object) = «ComboBox» Then objCoBx.Delete

Next objCoBx

‘delete all Form Control ComboBox objects in worksheet:

ws.DropDowns.Delete

Set rngSource = Range(«A2:D7»)

‘ListBox range / cell (rngComboBox) resized to add 2 columns

rngComboBox.Resize(rngComboBox.Rows.Count, rngComboBox.Columns.Count + 3).MergeCells = True

‘Range.ColumnWidth Property sets the width of all columns in the specified range

rngComboBox.Resize(1, rngComboBox.Columns.Count + 3).ColumnWidth = 7

‘Range.RowHeight Property returns or sets the height of the first row in the range, in points — to set or return the total height of a range of cells in points, use the Height property.

rngComboBox.RowHeight = 18

‘for an already existing ActiveX control ComboBox, with the name «ComboBox1»

‘Set objCoBx = ws.OLEObjects(«ComboBox1»)

‘set object variable to the newly added listbox ActiveX control

Set objCoBx = ws.OLEObjects.Add(ClassType:=»Forms.ComboBox.1«, DisplayAsIcon:=False, Left:=rngComboBox.Left, Top:=rngComboBox.Top, Width:=40, Height:=20)

With objCoBx

‘set a String value as name for the List Box

.Name = «ComboBox1«

‘LinkedCell property sets the worksheet range linked to the control’s value so that the linked cell displays the selected value from the ComboBox control

‘LinkedCell is 1 column to the right of the ComboBox cell

With rngComboBox.Offset(0, 1)

.NumberFormat = «#,##0.0«

.Value = ««

.Interior.Color = vbYellow

.HorizontalAlignment = xlCenter

End With

.linkedCell = rngComboBox.Offset(0, 1).Address

‘Object Property of the OLEObject returns a OLE Automation object associated with this OLE object

With .Object

‘display column headings (if combobox is filled with ListFillRange/RowSource)

.ColumnHeads = True

‘ColumnCount Property specifies the number of columns to be displayed in a ComboBox or ListBox. A ColumnCount value of 0 does not display any column and a setting of -1 displays all columns.

.ColumnCount = 3

‘set width of each column

.ColumnWidths = «50;40;40«

‘fmShowDropButtonWhenAlways — always shows the drop-down button; fmShowDropButtonWhenNever — never shows the drop-down button; fmShowDropButtonWhenFocus — shows the drop-down button only when the control has focus.

.ShowDropButtonWhen = fmShowDropButtonWhenAlways

‘Style Property determines choosing or setting the value of ComboBox (not valid for ListBox). There are 2 settings: (i) fmStyleDropDownCombo (value 0 — default) — user has both options of typing a custom value in the text area or select from the drop-down list; (ii) fmStyleDropDownList (value 2) — user can only select from the drop-down list, like in ListBox.

.Style = fmStyleDropDownCombo

‘enabling the DragBehavior property enables the drag-and-drop feature for ComboBox — dragging in combo box starts a drag-and-drop operation on the selected text but not in the drop-down portion — DragBehavior has no effect on a ComboBox whose Style property is set to fmStyleDropDownList

.DragBehavior = fmDragBehaviorEnabled

.BorderStyle = fmBorderStyleSingle

.BorderColor = RGB(255, 0, 0)

.MatchEntry = fmMatchEntryComplete

.ListStyle = fmListStyleOption

‘set background color

.BackColor = RGB(216, 216, 216)

‘set font color to blue

.ForeColor = RGB(0, 0, 255)

With .Font

.Name = «Arial»

.Bold = False

.Size = 9

.Italic = False

.Underline = False

End With

‘Populate ComboBox from an Array:

‘create a 2-dimensional array and load to ComboBox using the List property (copies an array without transposing it)

Dim myArray(5, 3)

‘Declaring the array and its dimensions. The array has been named myArray, of size 5 by 3 (5 rows by 3 columns). Note: When you populate an array with data, the array will start at zero, and if you include Option Base 1 the array will start at 1.

‘populate rows & columns of myArray, with worksheet range (rngSource)

For c = 0 To 2

For r = 0 To 5

myArray(r, c) = rngSource(r + 1, c + 1)

Next r

Next c

‘copy data to ComboBox using List property — copies an array without transposing it:

.List() = myArray

‘remove all items if ListFillRange has not been used to fill the combo box

If objCoBx.ListFillRange = «« Then

‘.Clear

‘deleting row from ListBox using RemoveItem method:

For i = .ListCount — 1 To 0 Step -1

.RemoveItem (i)

Next

Else

‘clear ComboBox if filled with ListFillRange/RowSource (if ListFillRange property has been used to specify the source of a list)

objCoBx.ListFillRange = ««

End If

‘ListFillRange property specifies the source of a list (which could be a worksheet range in Excel), for a ComboBox or ListBox.

objCoBx.ListFillRange = rngSource.Address

‘alternatively:

‘objCoBx.ListFillRange = «$A$2:$C$7«

‘objCoBx.ListFillRange = Range(«A2:C7»).Address

‘objCoBx.ListFillRange = «NamedRange«

‘TextColumn property enables display of one set of values to the user but store a different set of values (per column specified in the BoundColumn property).

‘TextColumn property specifies the column of data in a ComboBox that supplies data for its Text property — the TextColumn property determines the column whose value the Text property will return whereas the BoundColumn property determines the column whose value the Value property returns. The Text property returns the same as Value if the TextColumn property is not set. Setting the TextColumn value to -1 indicates that the first column with a ColumnWidths value greater than 0 will be displayed. Setting the TextColumn value to 0 returns the ListIndex value (the number of the selected row) in Text Property — this setting is useful if you want to determine the row of the selected item.

.TextColumn = 1

‘BoundColumn Property: Specifies the column from which value is to be stored in a multicolumn ComboBox or ListBox, when a row is selected by the user. First column has a BoundColumn value of 1

‘Setting the BoundColumn value to 0 assigns the value of the ListIndex property (which is the number of the selected row) as the value of the control (ComboBox or ListBox).

.BoundColumn = 4

‘ListIndex Property determines which item is selected in a ComboBox or ListBox. The first item in a list has a ListIndex value of 0, the second item has a value of 1, and so on.

.ListIndex = 2

‘Value Property: For the controls ComboBox and ListBox (value cannot be used with a multi-select ListBox), it is the value in the BoundColumn of the currently selected row (BoundColumn property specifies the column from which value is to be stored in a multicolumn ComboBox or ListBox, when a row is selected by the user).

MsgBox .Value

‘Using the ListCount property with the ListRows property, to set number of rows to display in ComboBox

‘ListCount Property determines the total number of rows in a ListBox or ComboBox.

If .ListCount > 5 Then

‘ListRows Property specifies the maximum number of rows which will display in the list box portion of a ComboBox. The default value is 8. Note: If the actual number of list items exceed this maximum value of the ListRows property, a vertical scroll bar will appear in the list box portion of the ComboBox (and the excess list items can be viewed by scrolling down).

.ListRows = 4

Else

.ListRows = .ListCount

End If

End With

‘size the ComboBox with the resized range

‘set column width in points

.Width = rngComboBox.Resize(rngComboBox.Rows.Count, rngComboBox.Columns.Count + 3).Width

‘Range.Height Property returns or sets the height of the range, in points

.Height = rngComboBox.Height

‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)

.Placement = xlFreeFloating

‘use the Locked Property of the Shapes object to lock it — if not Locked (False), the object can be modified when the sheet is protected

.Locked = True

‘enable the object

.Enabled = True

.Activate

End With

End Sub

Macro associated with the Click event of the ComboBox1: this Event-handler procedure must be located in the code module of the object worksheet containing the control (ComboBox1) — refer Image 5c

Private Sub ComboBox1_Click()
‘on clicking / selecting an item in the ActiveX Control ComboBox1 — refer Image 5c

On Error Resume Next

Dim cat As String, str As String, rng As Range, BMI As Single

Set rng = Range(«A10»)

rng.Resize(rng.Rows.Count, rng.Columns.Count + 2).MergeCells = True

‘Body Mass Index formula is — weight in kilograms divided by the square of height in meters: kg/m2

‘BMI Categories:

‘Underweight = <18.5

‘Normal weight = 18.5–24.9

‘Overweight = 25–29.9

‘Obesity = BMI of 30 or greater

‘assign Value property to BMI

BMI = ComboBox1.Object.Value

If BMI < 18.5 Then

cat = «Underweight»

ElseIf BMI < 25 Then

cat = «Normal Weight»

ElseIf BMI < 30 Then

cat = «Overweight»

ElseIf BMI >= 30 Then

cat = «Obese»

End If

With rng

.Interior.Color = vbGreen

.HorizontalAlignment = xlCenter

‘Combobox Text Property gives the Name, & BMI Category (cat) is derived from BMI (Combobox Value Property)

.Value = ComboBox1.Object.Text & » is » & cat

End With

End Sub

Option Button — Form Control or ActiveX Control

OptionButton is used to make one selection from multiple options. It is also referred to as a Radio Button, which chooses one option from a group of mutually exclusive options. If OptionButtons are not grouped, selecting one OptionButton will de-select all other OptionButtons. All OptionsButtons within a specific Group become mutually exclusive and self-contained within that group and do not affect selection of OptionButtons outside that group. Selecting an OptionButton in one group will de-select all other OptionButtons of only that group. The Value property of an OptionButton indicates whether it is selected or not. A True value indicates that the OptionButton is selected, False is the default value and indicates that it is not selected.

CheckBox vs OptionButton: With CheckBox, user can select multiple options, by selecting each CheckBox against which an option is available. OptionButton is used when user is allowed to select only a single option. CheckBox can be used in a singular manner viz. a single CheckBox can be selected or deselected (by clicking itself) indicating whether an option is to be exercised or not. OptionButton on the other hand are used in multiples viz. two or more, to indicate selection of mutually exculsive options. OptionButton gets deselected only on selection of another OptionButton and not by clicking itself.

Below we illustrate, a Form Control OptionButton, and an ActiveX Control OptionButton.

Example: Form Control Option Button:

Use Shapes.AddFormControl Method to create Excel Form Controls (Option Button & Group Box) — this returns a Shape object representing the new control — refer Image 6a

Sub FormControl_OptionButton_GroupBox_Shape_Properties()
‘use Shapes.AddFormControl Method to create Excel Form Controls (Option Button & Group Box) — this returns a Shape object representing the new control — refer Image 6a

Dim shpOptnBtn As Shape, ws As Worksheet, rngOptnBtn As Range, objOptnBtn As OLEObject

Set ws = Sheets(«Sheet1»)

ws.Activate

Set rngOptnBtn = Range(«B2»)

‘delete ActiveX Control OptionButton objects

For Each objOptnBtn In ActiveSheet.OLEObjects

‘TypeName Function returns the data-type about a variable — TypeName(varname)

If TypeName(objOptnBtn.Object) = «OptionButton» Then objOptnBtn.Delete

Next objOptnBtn

‘delete all (Form Control) Option Buttons in worksheet

ws.OptionButtons.Delete

‘delete all (Form Control) group boxes in worksheet

ws.GroupBoxes.Delete

rngOptnBtn.ColumnWidth = 11

rngOptnBtn.RowHeight = 17

‘for an already existing Form Control shape — Option Button, with the name «Option Button 1»

‘Set shpOptnBtn = ws.Shapes(«Option Button 1»)

‘set object variable to the newly added Option Button Form control — position & size the Option Button with the cell assigned to the rngOptnBtn variable

‘use Shapes.AddFormControl Method to create an Excel Form Control — this returns a Shape object representing the new control — Syntax: Shapes.AddFormControl(Type, Left, Top, Width, Height):

Set shpOptnBtn = ws.Shapes.AddFormControl(xlOptionButton, Left:=rngOptnBtn.Left, Top:=rngOptnBtn.Top, Width:=rngOptnBtn.Width, Height:=rngOptnBtn.Height)

With shpOptnBtn

‘set a String value as object’s name

.Name = «Option Button 1«

‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)

.Placement = xlFreeFloating

‘use the Locked Property of the Shapes object to lock it — if not Locked (False), the object can be modified when the sheet is protected

.Locked = True

‘shape will retain its original proportions when it is resized

.LockAspectRatio = msoTrue

‘wrt to the cell which is under the upper-left corner of the Option Button — enter text in the same row to the left of the Option Button

.TopLeftCell.Offset(0, -1) = «Country«

‘specify caption text

‘TextFrame Property returns a TextFrame object which contains the alignment & anchoring properties for a shape — valid for only a shape having a text frame

.TextFrame.Characters.Text = «USA«

‘set the alternative text to a shape description when Shape object is saved to a Web page — alternative text may be displayed in the web browser in lieu of the shape’s image, or over the shape’s image when the mouse pointer hovers over the image (if browser supported).

.AlternativeText = «Click to Select«

‘use the .OLEFormat.Object object to manipulate Display3DShading

.OLEFormat.Object.Display3DShading = False

‘ControlFormat property of the Shape object returns a ControlFormat object that contains Microsoft Excel control properties — the ControlFormat property will fail if the shape is not a control.

With .ControlFormat

.Enabled = True

‘OptionButton will be printed when the document is printed

.PrintObject = True

End With

‘set check box fill / interior

With .Fill

.Visible = msoTrue

.Solid

‘set background color to yellow

‘.ForeColor.SchemeColor = 13

.ForeColor.RGB = RGB(255, 255, 0)

.Transparency = 0

End With

‘set border for OptionButton

With .Line

.Weight = 1

.DashStyle = msoLineSolid

.Style = msoLineSingle

.Transparency = 0

.Visible = msoTrue

‘.ForeColor.SchemeColor = 10

.ForeColor.RGB = RGB(255, 0, 0)

End With

End With

‘————————————-

‘create second option button (by copying the first)

‘copy OptionButton and create new OptionButton with same properties

‘set range size, for cell below the existing OptionButton

rngOptnBtn.Offset(1, 0).RowHeight = rngOptnBtn.Height

‘copy check box to clipboard

ws.Shapes(«Option Button 1»).Copy

‘paste a copy of the OptionButton in the same sheet

ws.Paste

‘fit new OptionButton in the cell below the existing OptionButton

Selection.Left = rngOptnBtn.Offset(1, 0).Left

Selection.Top = rngOptnBtn.Offset(1, 0).Top

Selection.Name = «Option Button 2«

Selection.Characters.Text = «Canada«

‘alternatively

‘Selection.Caption = «Canada«

‘merge & format cells to the left of OptionButtons 1 & 2

Union(rngOptnBtn.Offset(0, -1), rngOptnBtn.Offset(1, -1)).Select

With Selection

.HorizontalAlignment = xlCenter

.VerticalAlignment = xlCenter

.ReadingOrder = xlContext

.MergeCells = True

.Interior.Color = RGB(0, 255, 0)

End With

‘———————-

‘create third & fourth option buttons (by copying the first)

‘copy OptionButton and create new OptionButton with same properties

‘set range size, for cell below the existing OptionButton

rngOptnBtn.Offset(3, 0).RowHeight = rngOptnBtn.Height

‘copy OptionButton1 to clipboard

ws.Shapes(«Option Button 1»).Copy

‘paste a copy of the OptionButton in the same sheet

ws.Paste

‘fit new OptionButton in the cell below the existing OptionButton

Selection.Left = rngOptnBtn.Offset(3, 0).Left

Selection.Top = rngOptnBtn.Offset(3, 0).Top

Selection.Name = «Option Button 3«

Selection.Caption = «Spain«

‘wrt to the cell which is under the upper-left corner of the Option Button — enter text in the same row to the left of the Option Button

Selection.TopLeftCell.Offset(0, -1) = «Country«

‘copy OptionButton and create new OptionButton with same properties

‘set range size, for cell below the existing OptionButton

rngOptnBtn.Offset(4, 0).RowHeight = rngOptnBtn.Height

‘copy OptionButton3 to clipboard

ws.Shapes(«Option Button 3»).Copy

‘paste a copy of the OptionButton in the same sheet

ws.Paste

‘fit new OptionButton in the cell below the existing OptionButton

Selection.Left = rngOptnBtn.Offset(4, 0).Left

Selection.Top = rngOptnBtn.Offset(4, 0).Top

Selection.Name = «Option Button 4«

Selection.Caption = «France«

‘merge & format cells to the left of OptionButtons 3 & 4

Union(rngOptnBtn.Offset(3, -1), rngOptnBtn.Offset(4, -1)).Select

With Selection

.HorizontalAlignment = xlCenter

.VerticalAlignment = xlCenter

.ReadingOrder = xlContext

.MergeCells = True

.Interior.Color = RGB(0, 255, 0)

End With

‘———————-

‘create 2 (Form Control) group boxes, to include 2 option buttons each

Dim rngGB1 As Range, rngGB2 As Range

‘resize the range for group box to include the range of first & second option buttons

Set rngGB1 = rngOptnBtn.Resize(rngOptnBtn.Rows.Count + 1, rngOptnBtn.Columns.Count)

‘resize the range for group box to include the the range of third & fourth option buttons

Set rngGB2 = rngOptnBtn.Offset(3, 0).Resize(rngOptnBtn.Rows.Count + 1, rngOptnBtn.Columns.Count)

‘add first Group Box — position & size the group box to include the option buttons 1 & 2

With ws.GroupBoxes.Add(Left:=rngGB1.Left, Top:=rngGB1.Top, Width:=rngGB1.Width, Height:=rngGB1.Height)

‘set group box name

.Name = «America«

‘do not display caption

.Characters.Text = ««

.Placement = xlFreeFloating

End With

‘add second Group Box — position & size the group box to include the option buttons 3 & 4

With ws.GroupBoxes.Add(Left:=rngGB2.Left, Top:=rngGB2.Top, Width:=rngGB2.Width, Height:=rngGB2.Height)

.Name = «Europe«

.Characters.Text = ««

.Placement = xlFreeFloating

End With

‘enter in the cell to the left of option buttons 1 & 3

ws.Shapes(«Option Button 1»).TopLeftCell.Offset(0, -1).Value = ws.GroupBoxes(1).Name

ws.Shapes(«Option Button 3»).TopLeftCell.Offset(0, -1).Value = ws.GroupBoxes(2).Name

‘you may use the same linked cell for all option buttons within a group, because the linked cell returns the number of the selected option button within in the group viz. the first option button within a group returns 1, the second option button returns 2, and so on. For multiple groups on a worksheet, use a different linked cell for each group of option buttons.

ws.Shapes(«Option Button 1»).ControlFormat.linkedCell = rngOptnBtn.Address

ws.Shapes(«Option Button 2»).ControlFormat.linkedCell = rngOptnBtn.Address

ws.Shapes(«Option Button 3»).ControlFormat.linkedCell = rngOptnBtn.Offset(3, 0).Address

ws.Shapes(«Option Button 4»).ControlFormat.linkedCell = rngOptnBtn.Offset(3, 0).Address

‘Value property of a OptionButton indicates whether it is selected or not.

‘select option buttons 1 & 4

ws.Shapes(«Option Button 1»).ControlFormat.Value = xlOn

ws.Shapes(«Option Button 4»).ControlFormat.Value = xlOn

Dim str As String

‘————————————

‘return the selected OptionButton’s caption & its GroupBox’ name — alternate 1:

‘Form Control OptionButton objects

‘For Each shpOptnBtn In ActiveSheet.Shapes

‘If shpOptnBtn.FormControlType = xlOptionButton Then

‘if option button is 1 or 2, & if selected

‘If (shpOptnBtn.Name = «Option Button 1» Or shpOptnBtn.Name = «Option Button 2») And shpOptnBtn.ControlFormat.Value = xlOn Then

‘return the selected OptionButton’s caption & its GroupBox’ name

‘str = str & «; » & shpOptnBtn.TextFrame.Characters.Text & » in » & ws.GroupBoxes(1).Name

‘End If

‘if option button is 3 or 4, & if selected

‘If (shpOptnBtn.Name = «Option Button 3» Or shpOptnBtn.Name = «Option Button 4») And shpOptnBtn.ControlFormat.Value = xlOn Then

‘return the selected OptionButton’s caption & its GroupBox’ name

‘str = str & «; » & shpOptnBtn.TextFrame.Characters.Text & » in » & ws.GroupBoxes(2).Name

‘End If

‘End If

‘Next

‘————————————

‘return the selected OptionButton’s caption & its GroupBox’ name — alternate 2:

‘Form Control OptionButton objects

For Each shpOptnBtn In ActiveSheet.Shapes

If shpOptnBtn.FormControlType = xlOptionButton Then

‘if option button range intersects with group box 1 range (ie. if option button is 1 or 2), & if selected

If Not Intersect(shpOptnBtn.TopLeftCell, rngGB1) Is Nothing And shpOptnBtn.ControlFormat.Value = 1 Then

‘return the selected OptionButton’s caption & its GroupBox’ name

str = str & «; » & shpOptnBtn.TextFrame.Characters.Text & » in » & ws.GroupBoxes(1).Name

End If

‘if option button range intersects with group box 2 range (ie. if option button is 3 or 4), & if selected

If Not Intersect(shpOptnBtn.TopLeftCell, rngGB2) Is Nothing And shpOptnBtn.ControlFormat.Value = 1 Then

‘return the selected OptionButton’s caption & its GroupBox’ name

str = str & «; » & shpOptnBtn.TextFrame.Characters.Text & » in » & ws.GroupBoxes(2).Name

End If

End If

Next

‘delete starting «;»

‘return the caption & group name of Selected option buttons

If Left(str, 1) = «;» Then

‘returns: «USA in America; France in Europe»

str = Right(str, Len(str) — 2)

MsgBox str

Else

MsgBox str

End If

End Sub

Example: ActiveX Control Option Button:

Add a new OLEObject to a sheet — ActiveX control (OptionButton) — set its properties by using the properties of an OLEObject object, & by using the Object property of the OLEObject object, set GroupName for Option Buttons — refer Image 6b

Sub ActiveXControl_OptionButton_OLEobject_Properties()
‘add a new OLEObject to a sheet — ActiveX control (OptionButton) — set its properties by using the properties of an OLEObject object, & by using the Object property of the OLEObject object — refer Image 6b
‘set a group name — OptionButtons having the same GroupName become mutually exclusive and selecting one OptionButton will de-select all other OptionButtons of that group

Dim ws As Worksheet, rngOptnBtn As Range

‘OLEObject is not used for Form Controls

Dim objOptnBtn As OLEObject

Set ws = Sheets(«Sheet1»)

ws.Activate

‘set range/cell for OptionButton

Set rngOptnBtn = Range(«B2»)

‘delete ActiveX Control OptionButton objects

For Each objOptnBtn In ActiveSheet.OLEObjects

‘TypeName Function returns the data-type about a variable — TypeName(varname)

If TypeName(objOptnBtn.Object) = «OptionButton» Then objOptnBtn.Delete

Next objOptnBtn

‘delete Form Control OptionButton objects

Dim sh As Shape

For Each sh In ActiveSheet.Shapes

If sh.Type = msoFormControl Then

If sh.FormControlType = xlOptionButton Then sh.Delete

End If

Next sh

‘delete all (Form Control) group boxes in worksheet

ws.GroupBoxes.Delete

rngOptnBtn.ColumnWidth = 11

rngOptnBtn.RowHeight = 17

‘for an already existing ActiveX control OptionButton, with the name «OptionButton1»

‘Set objOptnBtn = ws.OLEObjects(«OptionButton1»)

‘set object variable to the newly added OptionButton ActiveX control — position & size the OptionButton with the cell assigned to the rngOptnBtn variable

Set objOptnBtn = ws.OLEObjects.Add(ClassType:=»Forms.OptionButton.1«, DisplayAsIcon:=False, Left:=rngOptnBtn.Left, Top:=rngOptnBtn.Top, Width:=rngOptnBtn.Width, Height:=rngOptnBtn.Height)

With objOptnBtn

‘set a String value as object’s name

.Name = «OptionButton1«

‘returns the index number of the object within the collection of similar objects

‘MsgBox .Index

‘set shadow

.Shadow = True

‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)

.Placement = xlFreeFloating

‘use the Locked Property of the Shapes object to lock it — if not Locked (False), the object can be modified when the sheet is protected

.Locked = True

.Enabled = True

‘OptionButton will be printed when the document is printed

.PrintObject = True

‘LinkedCell Property specifies a cell to set or store the Value property — changing the value of the control will automatically update the linked cell & a change in the linked cell will update the value of the control.

‘.LinkedCell = «Sheet1!B2«

.linkedCell = rngOptnBtn.Address

‘wrt to the cell which is under the upper-left corner of the option button — enter text in the same row to the left of the option button

.TopLeftCell.Offset(0, -1) = «Country«

‘if the property is not listed under the OLEObject class in the Object Browser, then you must return the actual control object by using the Object property of the OLEObject object

‘Object Property of the OLEObject returns a OLE Automation object associated with this OLE object

With .Object

.TextAlign = fmTextAlignCenter

‘TripleState property if set to True, will enable OptionButton to have three possible values, including the Null value, besides True & False

.TripleState = False

‘Value property of a OptionButton indicates whether it is selected or not. True (integer value 1) indicates that the OptionButton is selected, False (value of 0) indicates that it is cleared; and the Null value indicates that it is neither selected nor cleared, and the OptionButton will appear shaded in this case. The value of TripleState property should be set to True for the OptionButton to have a Null value.

.Value = False

‘determines how the control visually appears

.SpecialEffect = fmButtonEffectFlat

‘specify how caption will appear relative to the control

.Alignment = fmAlignmentLeft

‘Accelerator Property sets the key to access a control

.Accelerator = «h«

‘specify type of mouse pointer

.MousePointer = fmMousePointerArrow

‘load a picture to be displayed on the ActiveX control

.Picture = LoadPicture(«C:UsersamitDocumentsPhotosDollar.jpg»)

‘alignment of the picture with its caption

.PicturePosition = fmPicturePositionAboveCenter

‘remove picture

.Picture = LoadPicture(«»)

‘specify caption text

.Caption = «USA«

‘caption text will wrap to the next line

.WordWrap = True

‘setting AutoSize to True automatically resizes the Caption while False (Default option) keeps the caption size constant wherein content exceeding the control area gets cut.

.AutoSize = False

‘set background color to yellow

.BackColor = RGB(255, 255, 0)

‘set font color to red

.ForeColor = RGB(255, 0, 0)

‘set background to be Opaque or Transparent — BackStyle property should be set to fmBackStyleOpaque for the BackColor to have any effect

.BackStyle = fmBackStyleOpaque

With .Font

.Name = «Arial»

.Bold = True

.Size = 10

.Italic = False

.Underline = False

End With

End With

End With

‘———————-

‘copy OptionButton and create new OptionButton with same properties

‘set range size, for cell below the existing OptionButton

rngOptnBtn.Offset(1, 0).ColumnWidth = rngOptnBtn.ColumnWidth

rngOptnBtn.Offset(1, 0).RowHeight = rngOptnBtn.Height

‘copy OptionButton1 to clipboard

ws.OLEObjects(«OptionButton1»).Copy

‘paste a copy of the OptionButton in the same sheet

ws.Paste

‘fit new OptionButton in the cell below the existing OptionButton

Selection.Left = rngOptnBtn.Offset(1, 0).Left

Selection.Top = rngOptnBtn.Offset(1, 0).Top

Selection.Name = «OptionButton2«

ws.OLEObjects(«OptionButton2»).linkedCell = rngOptnBtn.Offset(1, 0).Address

ws.OLEObjects(«OptionButton2»).Object.Caption = «Canada«

‘merge & format cells to the left of both OptionButtons

Union(rngOptnBtn.Offset(0, -1), rngOptnBtn.Offset(1, -1)).Select

With Selection

.HorizontalAlignment = xlCenter

.VerticalAlignment = xlCenter

.ReadingOrder = xlContext

.MergeCells = True

.Interior.Color = RGB(0, 255, 0)

End With

‘———————-

‘copy OptionButton and create new OptionButton with same properties

‘set range size, for cell below the existing OptionButton

rngOptnBtn.Offset(3, 0).ColumnWidth = rngOptnBtn.ColumnWidth

rngOptnBtn.Offset(3, 0).RowHeight = rngOptnBtn.Height

‘copy OptionButton1 to clipboard

ws.OLEObjects(«OptionButton1»).Copy

‘paste a copy of the OptionButton in the same sheet

ws.Paste

‘fit new OptionButton in the cell below the existing OptionButton

Selection.Left = rngOptnBtn.Offset(3, 0).Left

Selection.Top = rngOptnBtn.Offset(3, 0).Top

Selection.Name = «OptionButton3»

ws.OLEObjects(«OptionButton3»).linkedCell = rngOptnBtn.Offset(3, 0).Address

ws.OLEObjects(«OptionButton3»).Object.Caption = «Spain«

‘wrt to the cell which is under the upper-left corner of the option button

ws.OLEObjects(«OptionButton3»).TopLeftCell.Offset(0, -1) = «Country«

‘copy OptionButton and create new OptionButton with same properties

‘set range size, for cell below the existing OptionButton

rngOptnBtn.Offset(4, 0).ColumnWidth = rngOptnBtn.ColumnWidth

rngOptnBtn.Offset(4, 0).RowHeight = rngOptnBtn.Height

‘copy OptionButton3 to clipboard

ws.OLEObjects(«OptionButton3»).Copy

‘paste a copy of the OptionButton in the same sheet

ws.Paste

‘fit new OptionButton in the cell below the existing OptionButton

Selection.Left = rngOptnBtn.Offset(4, 0).Left

Selection.Top = rngOptnBtn.Offset(4, 0).Top

Selection.Name = «OptionButton4»

ws.OLEObjects(«OptionButton4»).linkedCell = rngOptnBtn.Offset(4, 0).Address

ws.OLEObjects(«OptionButton4»).Object.Caption = «France»

‘merge & format cells to the left of OptionButtons 3 & 4

Union(rngOptnBtn.Offset(3, -1), rngOptnBtn.Offset(4, -1)).Select

With Selection

.HorizontalAlignment = xlCenter

.VerticalAlignment = xlCenter

.ReadingOrder = xlContext

.MergeCells = True

.Interior.Color = RGB(0, 255, 0)

End With

‘———————-

‘use the GroupName property to set a group name for an option button — OptionButtons having the same GroupName become mutually exclusive and selecting one OptionButton will de-select all other OptionButtons of that group

ws.OLEObjects(«OptionButton1»).Object.GroupName = «America«

ws.OLEObjects(«OptionButton2»).Object.GroupName = «America«

ws.OLEObjects(«OptionButton3»).Object.GroupName = «Europe«

ws.OLEObjects(«OptionButton4»).Object.GroupName = «Europe«

‘enter group names on the left of option buttons

ws.OLEObjects(«OptionButton1»).TopLeftCell.Offset(0, -1) = «America«

ws.OLEObjects(«OptionButton3»).TopLeftCell.Offset(0, -1) = «Europe«

‘select option buttons 2 & 4

ws.OLEObjects(«OptionButton2»).Object = True

ws.OLEObjects(«OptionButton4»).Object = True

Dim str As String

‘ActiveX Control OptionButton objects

For Each objOptnBtn In ActiveSheet.OLEObjects

‘TypeName Function returns the data-type about a variable — TypeName(varname)

If TypeName(objOptnBtn.Object) = «OptionButton» Then

If objOptnBtn.Object.GroupName = «America» And objOptnBtn.Object.Value = True Then

str = str & «; » & objOptnBtn.Object.Caption & » in America»

End If

If objOptnBtn.Object.GroupName = «Europe» And objOptnBtn.Object.Value = True Then

str = str & «; » & objOptnBtn.Object.Caption & » in Europe»

End If

End If

Next

‘delete starting «;»

‘return the caption & group name of Selected option buttons

If Left(str, 1) = «;» Then

‘returns: «USA in America; France in Europe»

str = Right(str, Len(str) — 2)

rngOptnBtn.Offset(6, -1).Value = str

Else

rngOptnBtn.Offset(6, -1).Value = str

End If

End Sub

Toggle Button — ActiveX Control

ToggleButton is a control which executes one action when clicked first and a different action on the second click. It has two states, On & Off, wherein the button alternates (or toggles) between the two. It can have a value of True (where it appears as pressed) when the button is selected or the value False (appears unpressed) when unselected.

Below we illustrate an ActiveX Control ToggleButton a Macro associated with the Click event of this ToggleButton.

Example: ActiveX Control Toggle Button:

Add a new OLEObject to a sheet — ActiveX control (ToggleButton) — set its properties by using the properties of an OLEObject object, & by using the Object property of the OLEObject object — refer Image 7a

Sub ActiveXControl_ToggleButton_OLEobject_Properties()
‘add a new OLEObject to a sheet — ActiveX control (ToggleButton) — set its properties by using the properties of an OLEObject object, & by using the Object property of the OLEObject object — refer Image 7a

Dim ws As Worksheet, rngTglBtn As Range

‘OLEObject is not used for Form Controls

Dim objTglBtn As OLEObject

Set ws = Sheets(«Sheet1»)

ws.Activate

‘set range/cell for ToggleButton

Set rngTglBtn = Range(«B2»)

‘delete ActiveX Control ToggleButton objects

For Each objTglBtn In ActiveSheet.OLEObjects

‘TypeName Function returns the data-type about a variable — TypeName(varname)

If TypeName(objTglBtn.Object) = «ToggleButton» Then objTglBtn.Delete

Next objTglBtn

rngTglBtn.ColumnWidth = 22

rngTglBtn.RowHeight = 24

‘for an already existing ActiveX control ToggleButton, with the name «ToggleButton1»

‘Set objTglBtn = ws.OLEObjects(«ToggleButton1»)

‘set object variable to the newly added ToggleButton ActiveX control — position & size the ToggleButton with the cell assigned to the rngTglBtn variable

Set objTglBtn = ws.OLEObjects.Add(ClassType:=»Forms.ToggleButton.1«, DisplayAsIcon:=False, Left:=rngTglBtn.Left, Top:=rngTglBtn.Top, Width:=rngTglBtn.Width, Height:=rngTglBtn.Height)

With objTglBtn

‘set a String value as object’s name

.Name = «ToggleButton1«

‘set shadow

.Shadow = True

‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)

.Placement = xlFreeFloating

‘use the Locked Property of the Shapes object to lock it — if not Locked (False), the object can be modified when the sheet is protected

.Locked = True

.Enabled = True

‘toggle buttonwill be printed when the document is printed

.PrintObject = True

‘LinkedCell Property specifies a cell to set or store the Value property — changing the value of the control will automatically update the linked cell & a change in the linked cell will update the value of the control.

‘TopLeftCell — wrt to the cell which is under the upper-left corner of the toggle button

.linkedCell = .TopLeftCell.Offset(0, -1).Address

‘if the property is not listed under the OLEObject class in the Object Browser, then you must return the actual control object by using the Object property of the OLEObject object

‘Object Property of the OLEObject returns a OLE Automation object associated with this OLE object

With .Object

.TextAlign = fmTextAlignCenter

‘TripleState property if set to True, will enable ToggleButton to have three possible values, including the Null value, besides True & False

.TripleState = False

‘Value property of a ToggleButton indicates whether it is selected or not. True (integer value 1) indicates that the ToggleButton is selected & where it appears as pressed, False (value of 0) indicates that it is unselected where it appears as unpressed; and the Null value indicates that it is neither selected nor cleared, and the ToggleButton will appear shaded in this case. The value of TripleState property should be set to True for the ToggleButton to have a Null value.

.Value = False

‘Accelerator Property sets the key to access a control

.Accelerator = «h«

‘specify type of mouse pointer

.MousePointer = fmMousePointerArrow

‘load a picture into ActiveX control, using the LoadPicture Function — specify filename & address of image to be loaded

.Picture = LoadPicture(«C:UsersamitDocumentsPhotosDollar.jpg»)

‘alignment of the picture with its caption

.PicturePosition = fmPicturePositionAboveCenter

‘remove picture

.Picture = LoadPicture(«»)

‘specify caption text

.Caption = «Sort Data«

‘caption text will wrap to the next line

.WordWrap = True

‘setting AutoSize to True automatically resizes the Caption while False (Default option) keeps the caption size constant wherein content exceeding the control area gets cut.

.AutoSize = False

‘set the background color for control to yellow

.BackColor = RGB(255, 255, 0)

‘set font color to black

.ForeColor = RGB(0, 0, 0)

‘set background to be Opaque or Transparent — BackStyle property should be set to fmBackStyleOpaque for the BackColor to have any effect

.BackStyle = fmBackStyleOpaque

With .Font

.Name = «Arial«

.Bold = True

.Size = 10

.Italic = True

.Underline = False

End With

End With

End With

End Sub

Macro associated with the Click event of the ToggleButton1: this Event-handler procedure must be located in the code module of the object worksheet containing the control (ToggleButton1) — refer Image 7b

Private Sub ToggleButton1_Click()
‘ToggleButton control generates a Click event for which an event-handler sub procedure has been written here — refer Image 7b
‘ToggleButton is a control which executes one action when clicked first and a different action on the second click. It has two states, On & Off, wherein the button alternates (or toggles) between the two. It can have a value of True (where it appears as pressed) when the button is selected or the value False (appears unpressed) when unselected.

Dim lTotalRows As Long, ws As Worksheet

‘determine total rows in column D:

lTotalRows = Cells(Rows.Count, «D»).End(xlUp).Row

‘if ToggleButton value is True: it appears pressed — data in column D appears sorted in Descending order — button appears in green BackColor and displays the alternate sort option («Get Ascending Order»):

If ToggleButton1.Value = True Then

ToggleButton1.Caption = «Get Ascending Order«

ToggleButton1.BackColor = RGB(0, 255, 0)

Range(«D2:D» & lTotalRows).Sort key1:=Range(«D2»), order1:=xlDescending

‘if ToggleButton value is False: it appears unpressed — data in column D appears sorted in Ascending order — button appears in red BackColor and displays the alternate sort option («Get Decending Order»):

ElseIf ToggleButton1.Value = False Then

ToggleButton1.Caption = «Get Decending Order«

ToggleButton1.BackColor = RGB(255, 0, 0)

Range(«D2:D» & lTotalRows).Sort key1:=Range(«D2»), order1:=xlAscending

End If

End Sub

ScrollBar & SpinButton Controls — Form Control or ActiveX Control

A ScrollBar control enables to scroll through a range of values when a user: (i) clicks on the scroll arrows; (ii) drags the scroll box; or (iii) clicks in an area between a scroll arrow and the scroll box. Both ScrollBar control & SpinButton control enable to change (increment or decrement) value in a worksheet range. SpinButton control (also referred to as a Spinner control) functions like a ScrollBar control, with similar properties (viz. SmallChange, Min, Max, Orientation, …). Difference between the ScrollBar & SpinButton controls is that the ScrollBar box can be dragged to change the control’s value over larger increments (while keeping the increment low for clicks) which advantages a ScrollBar to make a selection from across a large number of values and cover an extremely wide range. SpinButton control does not have a LargeChange property, like in a ScrollBar, which specifies the incremental change when the user clicks between a scroll arrow and the scroll box.

Below we illustrate: (i) a Form Control Scroll Bar & and assign it to a Macro; and (ii) an ActiveX Control ScrollBar & Macro associated with the Change event of this ScrollBar.

Example: Form Control Scroll Bar & Macro to which it is assigned:

Create an Excel Form Control (Scroll Bar) & set ScrollBar properties — use Shapes.AddFormControl Method to create an Excel Form Control which returns a Shape object representing the new control — Refer Image 8a

Sub FormControl_ScrollBar_Shape_Properties()
‘use Shapes.AddFormControl Method to create an Excel Form Control (ScrollBar) — this returns a Shape object representing the new control — refer Image 8a
‘Creating a Mortgage Calculator, using ScrollBar controls: Loan Amount ($)in cell B2 & its «Scroll Bar 1» in cell C2; Annual Interest (%) in cell B3 & its «Scroll Bar 2» in cell C3; Loan Tenure (Yrs) in cell B4 & its «Scroll Bar 3» in cell C4; Mthly Instalment ($) in cell B5.

Dim ws As Worksheet, shpScrlBar As Shape, objScrlBar As OLEObject

Dim rngScrlBar1 As Range, rngScrlBar2 As Range, rngScrlBar3 As Range

Set ws = Sheets(«Sheet1»)

ws.Activate

‘set range/cell for ScrollBar

Set rngScrlBar1 = Range(«C2»)

Set rngScrlBar2 = Range(«C3»)

Set rngScrlBar3 = Range(«C4»)

‘format cells

With rngScrlBar1.Offset(0, -1).Resize(1, 2)

.Value = ««

.NumberFormat = «$#,##0«

End With

With rngScrlBar2.Offset(0, -1).Resize(2, 2)

.Value = ««

.NumberFormat = «0.0«

End With

With rngScrlBar3.Offset(1, -1)

.Value = «»

.NumberFormat = «$#,##0«

End With

‘delete ActiveX Control ScrollBar objects

For Each objScrlBar In ActiveSheet.OLEObjects

‘TypeName Function returns the data-type about a variable — TypeName(varname)

If TypeName(objScrlBar.Object) = «ScrollBar» Then objScrlBar.Delete

Next objScrlBar

‘delete Form Control ScrollBar objects

For Each shpScrlBar In ActiveSheet.Shapes

If shpScrlBar.Type = msoFormControl Then

If shpScrlBar.FormControlType = xlScrollBar Then shpScrlBar.Delete

End If

Next shpScrlBar

rngScrlBar1.ColumnWidth = 15

rngScrlBar1.RowHeight = 15

‘for an already existing Form Control shape — ScrollBar, with the name «Scroll Bar 1»

‘Set shpScrlBar = ws.Shapes(«Scroll Bar 1»)

‘set object variable to the newly added check box Form control — position & size the ScrollBar with the cell assigned to the rngScrlBar1 variable

‘use Shapes.AddFormControl Method to create an Excel Form Control — this returns a Shape object representing the new control — Syntax: Shapes.AddFormControl(Type, Left, Top, Width, Height):

‘a scroll bar gets oriented (horizontal or vertical) based on its size on the worksheet, whereas an ActiveX scroll bar has an Orientation property which can be set to be Auto, Horizontal, or Vertical

Set shpScrlBar = ws.Shapes.AddFormControl(xlScrollBar, Left:=rngScrlBar1.Left, Top:=rngScrlBar1.Top, Width:=rngScrlBar1.Width, Height:=rngScrlBar1.Height)

With shpScrlBar

‘set a String value as object’s name

.Name = «Scroll Bar 1«

‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)

.Placement = xlFreeFloating

‘use the Locked Property of the Shapes object to lock it — if not Locked (False), the object can be modified when the sheet is protected

.Locked = True

‘shape will retain its original proportions when it is resized

.LockAspectRatio = msoTrue

‘set the alternative text to a shape description when Shape object is saved to a Web page — alternative text may be displayed in the web browser in lieu of the shape’s image, or over the shape’s image when the mouse pointer hovers over the image (if browser supported).

.AlternativeText = «Scroll«

‘use the Shape.OnAction Property to assign a macro (ie. sets the macro name) to the shape — clicking on the shape will execute the ScrollBar_CalcPMT macro

.OnAction = «ScrollBar_CalcPMT«

‘ControlFormat property of the Shape object returns a ControlFormat object that contains Microsoft Excel control properties — the ControlFormat property will fail if the shape is not a control.

With .ControlFormat

.Enabled = True

‘scroll bar will be printed when the document is printed

.PrintObject = True

‘LinkedCell Property specifies a cell to set or store the Value property ie. the current value corresponding to the position of the scroll box — changing the value of the control will automatically update the linked cell & a change in the linked cell will update the value of the control.

.linkedCell = rngScrlBar1.Address

‘specify the minimum and maximum acceptable values (as integer) of the ScrollBar control (for the Value property setting), value of the Max property must be greater than the value of the Min property

.Min = 0

.Max = 10000

‘SmallChange Property specifies the incremental change, as an integer value, that occurs when a user clicks the scroll arrow. Default value is 1.

.SmallChange = 5

‘LargeChange Property specifies the incremental change, as an integer value, when the user clicks between a scroll arrow and the scroll box. Default value is 1.

.LargeChange = 100

‘Value property sets the control’s current value, which is an integer between maximum & minimum values specified in the Max and Min properties

.Value = 1000

End With

End With

‘———————-

‘2nd ScrollBar: copy ScrollBar and create second ScrollBar with same properties

‘set range size, for cell below the existing ScrollBar

rngScrlBar2.ColumnWidth = rngScrlBar1.ColumnWidth

rngScrlBar2.RowHeight = rngScrlBar1.Height

‘copy ScrollBar1 to clipboard

ws.Shapes(«Scroll Bar 1»).Copy

‘paste a copy of the ScrollBar in the same sheet

ws.Paste

‘fit new ScrollBar in the cell below the existing ScrollBar

Selection.Left = rngScrlBar2.Left

Selection.Top = rngScrlBar2.Top

Selection.Name = «Scroll Bar 2«

‘use the Shape.OnAction Property to assign a macro (ie. sets the macro name) to the shape — clicking on the shape will execute the ScrollBar_CalcPMT macro

Selection.OnAction = «ScrollBar_CalcPMT«

With ws.Shapes(«Scroll Bar 2»).ControlFormat

.linkedCell = rngScrlBar2.Address

.Min = 0

.Max = 500

.SmallChange = 1

.LargeChange = 10

.Value = 50

End With

‘———————-

‘3rd ScrollBar: copy ScrollBar and create third ScrollBar with same properties

‘set range size, for cell below the existing ScrollBar

rngScrlBar3.ColumnWidth = rngScrlBar1.ColumnWidth

rngScrlBar3.RowHeight = rngScrlBar1.Height

‘copy ScrollBar1 to clipboard

ws.Shapes(«Scroll Bar 1»).Copy

‘paste a copy of the ScrollBar in the same sheet

ws.Paste

‘fit new ScrollBar in the cell below the existing ScrollBar

Selection.Left = rngScrlBar3.Left

Selection.Top = rngScrlBar3.Top

Selection.Name = «Scroll Bar 3«

‘use the Shape.OnAction Property to assign a macro (ie. sets the macro name) to the shape — clicking on the shape will execute the ScrollBar_CalcPMT macro

Selection.OnAction = «ScrollBar_CalcPMT«

With ws.Shapes(«Scroll Bar 3»).ControlFormat

.linkedCell = rngScrlBar3.Address

.Min = 0

.Max = 60
.SmallChange = 1

.LargeChange = 4

.Value = 20

End With

‘calculate monthly instalment in cell B5, by calling the macro ScrollBar_CalcPMT:

Call ScrollBar_CalcPMT

End Sub

This macro ( located in a standard module of the workbook) has been assigned to the scroll bars — «Scroll Bar 1» & «Scroll Bar 2» & «Scroll Bar 3» — & will execute when respective scrollbar value changes — refer Image 8a.

Sub ScrollBar_CalcPMT()
‘this macro has been assigned to the scroll bars — «Scroll Bar 1» & «Scroll Bar 2» & «Scroll Bar 3» — & will execute when respective scrollbar value changes — refer Image 8a
‘Creating a Mortgage Calculator, using ScrollBar controls: Loan Amount ($) in cell B2 & its «Scroll Bar 1» in cell C2; Annual Interest (%) in cell B3 & its «Scroll Bar 2» in cell C3; Loan Tenure (Yrs) in cell B4 & its «Scroll Bar 3» in cell C4; Mthly Instalment ($) in cell B5.

Dim ws As Worksheet, shpScrlBar1 As Shape, shpScrlBar2 As Shape, shpScrlBar3 As Shape

Dim rngScrlBar1 As Range, rngScrlBar2 As Range, rngScrlBar3 As Range

Set ws = Sheets(«Sheet1»)

ws.Activate

Set shpScrlBar1 = ws.Shapes(«Scroll Bar 1»)

Set shpScrlBar2 = ws.Shapes(«Scroll Bar 2»)

Set shpScrlBar3 = ws.Shapes(«Scroll Bar 3»)

‘set range/cell for ScrollBar

‘cell C2

Set rngScrlBar1 = Range(shpScrlBar1.ControlFormat.linkedCell)

‘cell C3

Set rngScrlBar2 = Range(shpScrlBar2.ControlFormat.linkedCell)

‘cell C4

Set rngScrlBar3 = Range(shpScrlBar3.ControlFormat.linkedCell)

‘in re of Loan Amount, clicking the scroll arrow will increment amount by $5,000 and clicking between a scroll arrow and the scroll box will increment amount by $100,000:

rngScrlBar1.Offset(0, -1).Value = shpScrlBar1.ControlFormat.Value * 1000

‘in re of Annual Interest Rate, clicking the scroll arrow will increment rate by 0.1% and clicking between a scroll arrow and the scroll box will increment rate by 1%:

rngScrlBar2.Offset(0, -1).Value = shpScrlBar2.ControlFormat.Value / 10

‘in re of Loan Tenure, clicking the scroll arrow will increment year by 0.5 and clicking between a scroll arrow and the scroll box will increment year by 2:

rngScrlBar3.Offset(0, -1).Value = shpScrlBar3.ControlFormat.Value / 2

If Not rngScrlBar1.Offset(0, -1).Value > 0 Then

MsgBox «Please Enter Loan Amount!»

Exit Sub

ElseIf Not rngScrlBar2.Offset(0, -1).Value > 0 Then

MsgBox «Please Enter Annual Interest Rate!»

Exit Sub

ElseIf Not rngScrlBar3.Offset(0, -1).Value > 0 Then

MsgBox «Please Enter Loan Tenure!»

Exit Sub

End If

‘calculate monthly instalment in cell B5:

rngScrlBar3.Offset(1, -1).Value = Pmt((rngScrlBar2.Offset(0, -1).Value / 100) / 12, rngScrlBar3.Offset(0, -1).Value * 12, rngScrlBar1.Offset(0, -1).Value) * -1

End Sub

Example: ActiveX Control ScrollBar(s) & Macro associated with the Change event of the ScrollBar(s):

Add a new OLEObject to a sheet — ActiveX control (ScrollBar) — set its properties by using the properties of an OLEObject object, & by using the Object property of the OLEObject object — Refer Image 8b

Sub ActiveXControl_ScrollBar_OLEobject_Properties()
‘add a new OLEObject to a sheet — ActiveX control (ScrollBar) — set its properties by using the properties of an OLEObject object, & by using the Object property of the OLEObject object — refer Image 8b
‘ScrollBar control enables to change (increment or decrement) value in a worksheet range
‘Creating a Mortgage Calculator, using ScrollBar controls: Loan Amount ($)in cell B2 & its ScrollBar1 in cell C2; Annual Interest (%) in cell B3 & its ScrollBar2 in cell C3; Loan Tenure (Yrs) in cell B4 & its ScrollBar3 in cell C4; Mthly Instalment ($) in cell B5.

Dim ws As Worksheet, rngScrlBar1 As Range, rngScrlBar2 As Range, rngScrlBar3 As Range

‘OLEObject is not used for Form Controls

Dim objScrlBar As OLEObject

Set ws = Sheets(«Sheet1»)

ws.Activate

‘set range/cell for ScrollBar

Set rngScrlBar1 = Range(«C2»)

Set rngScrlBar2 = Range(«C3»)

Set rngScrlBar3 = Range(«C4»)

With rngScrlBar1.Offset(0, -1).Resize(1, 2)

.Value = ««

.NumberFormat = «$#,##0«

End With

With rngScrlBar2.Offset(0, -1).Resize(2, 2)

.Value = ««

.NumberFormat = «0.0«

End With

With rngScrlBar3.Offset(1, -1)

.Value = «»

.NumberFormat = «$#,##0«

End With

‘delete ActiveX Control ScrollBar objects

For Each objScrlBar In ActiveSheet.OLEObjects

‘TypeName Function returns the data-type about a variable — TypeName(varname)

If TypeName(objScrlBar.Object) = «ScrollBar» Then objScrlBar.Delete

Next objScrlBar

‘delete all (Form Control) Scroll Bars in worksheet

ws.ScrollBars.Delete

rngScrlBar1.ColumnWidth = 15

rngScrlBar1.RowHeight = 15

‘for an already existing ActiveX control ScrollBar, with the name «ScrollBar1»

‘Set objScrlBar = ws.OLEObjects(«ScrollBar1»)

‘set object variable to the newly added ScrollBar ActiveX control — position & size the ScrollBar with the cell assigned to the rngScrlBar1 variable

Set objScrlBar = ws.OLEObjects.Add(ClassType:=»Forms.ScrollBar.1«, DisplayAsIcon:=False, Left:=rngScrlBar1.Left, Top:=rngScrlBar1.Top, Width:=rngScrlBar1.Width, Height:=rngScrlBar1.Height)

With objScrlBar

‘set a String value as object’s name

.Name = «ScrollBar1»

‘set shadow

.Shadow = True

‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)

.Placement = xlFreeFloating

‘use the Locked Property of the Shapes object to lock it — if not Locked (False), the object can be modified when the sheet is protected

.Locked = True

.Enabled = True

‘scroll bar will be printed when the document is printed

.PrintObject = True

‘LinkedCell Property specifies a cell to set or store the Value property — changing the value of the control will automatically update the linked cell & a change in the linked cell will update the value of the control.

.linkedCell = rngScrlBar1.Address

‘if the property is not listed under the OLEObject class in the Object Browser, then you must return the actual control object by using the Object property of the OLEObject object

‘Object Property of the OLEObject returns a OLE Automation object associated with this OLE object

With .Object

‘specify the minimum and maximum acceptable values (as integer) of the ScrollBar control (for the Value property setting)

.Min = 0

.Max = 10000

‘Orientation Property determines a vertical ScrollBar or a horizontal ScrollBar. It has 3 settings: (i) fmOrientationAuto (Value -1, default) — ScrollBar dimensions automatically determine whether the ScrollBar is Vertical or Horizontal. Where width is more than height, ScrollBar is Horizontal and where height is more than width, ScrollBar is Vertical; (ii) FmOrientationVertical (Value 0) — vertical ScrollBar; and (iii) FmOrientationHorizontal (Value 1) — horizontal ScrollBar.

.Orientation = fmOrientationHorizontal

‘SmallChange Property specifies the incremental change, as an integer value, that occurs when a user clicks the scroll arrow. Default value is 1.

.SmallChange = 5

‘LargeChange Property specifies the incremental change, as an integer value, when the user clicks between a scroll arrow and the scroll box. Default value is 1.

.LargeChange = 100
‘Value property sets the control’s current value, which is an integer between maximum & minimum values specified in the Max and Min properties

.Value = 0

‘specify type of mouse pointer

.MousePointer = fmMousePointerArrow

‘set background color to yellow

.BackColor = RGB(255, 255, 0)

‘set scroll arrow color to red

.ForeColor = RGB(255, 0, 0)

End With

End With

‘———————-

‘2nd ScrollBar: copy ScrollBar and create new ScrollBar with same properties

‘set range size, for cell below the existing ScrollBar

rngScrlBar2.ColumnWidth = rngScrlBar1.ColumnWidth

rngScrlBar2.RowHeight = rngScrlBar1.Height

‘copy ScrollBar1 to clipboard

ws.OLEObjects(«ScrollBar1»).Copy

‘paste a copy of the ScrollBar in the same sheet

ws.Paste

‘fit new ScrollBar in the cell below the existing ScrollBar

Selection.Left = rngScrlBar2.Left

Selection.Top = rngScrlBar2.Top

Selection.Name = «ScrollBar2«

ws.OLEObjects(«ScrollBar2»).linkedCell = rngScrlBar2.Address

With ws.OLEObjects(«ScrollBar2»).Object

.Min = 0

.Max = 500

.SmallChange = 1

.LargeChange = 10

.Value = 0

End With

‘———————-

‘3rd ScrollBar: copy ScrollBar and create new ScrollBar with same properties

‘set range size, for cell below the existing ScrollBar

rngScrlBar3.ColumnWidth = rngScrlBar1.ColumnWidth

rngScrlBar3.RowHeight = rngScrlBar1.Height

‘copy ScrollBar1 to clipboard

ws.OLEObjects(«ScrollBar1»).Copy

‘paste a copy of the ScrollBar in the same sheet

ws.Paste

‘fit new ScrollBar in the cell below the existing ScrollBar

Selection.Left = rngScrlBar3.Left

Selection.Top = rngScrlBar3.Top

Selection.Name = «ScrollBar3«

ws.OLEObjects(«ScrollBar3»).linkedCell = rngScrlBar3.Address

With ws.OLEObjects(«ScrollBar3»).Object

.Min = 0

.Max = 60

.SmallChange = 1

.LargeChange = 4

.Value = 0

End With

End Sub

Macro associated with the Change event of the ScrollBar1: this Event-handler procedure must be located in the code module of the object worksheet containing the control (ScrollBar1)

Private Sub ScrollBar1_Change()
‘Loan Amount ($) in cell B2 & its ScrollBar1 in cell C2

‘calculate monthly instalment:

Call CalcPMT

End Sub

Macro associated with the Change event of the ScrollBar2: this Event-handler procedure must be located in the code module of the object worksheet containing the control (ScrollBar2)

Private Sub ScrollBar2_Change()
‘Annual Interest (%) in cell B3 & its ScrollBar2 in cell C3

‘calculate monthly instalment:

Call CalcPMT

End Sub

Macro associated with the Change event of the ScrollBar3: this Event-handler procedure must be located in the code module of the object worksheet containing the control (ScrollBar3)

Private Sub ScrollBar3_Change()
‘Loan Tenure (Yrs) in cell B4 & its ScrollBar3 in cell C4

‘calculate monthly instalment:

Call CalcPMT

End Sub

Macro called by the Change events of the 3 ScrollBars: this Event-handler procedure must be located in the code module of the object worksheet containing the controls (ScrollBars) — refer Image 8c.

Sub CalcPMT()
‘Creating a Mortgage Calculator, using ScrollBar controls: Loan Amount ($) in cell B2 & its ScrollBar1 in cell C2; Annual Interest (%) in cell B3 & its ScrollBar2 in cell C3; Loan Tenure (Yrs) in cell B4 & its ScrollBar3 in cell C4; Mthly Instalment ($) in cell B5.

Dim rngScrlBar1 As Range, rngScrlBar2 As Range, rngScrlBar3 As Range

‘set range/cell for ScrollBar

‘cell C2

Set rngScrlBar1 = Range(ScrollBar1.linkedCell)

‘cell C3

Set rngScrlBar2 = Range(ScrollBar2.linkedCell)

‘cell C4

Set rngScrlBar3 = Range(ScrollBar3.linkedCell)

‘in re of Loan Amount, clicking the scroll arrow will increment amount by $5,000 and clicking between a scroll arrow and the scroll box will increment amount by $100,000:

rngScrlBar1.Offset(0, -1).Value = ScrollBar1.Value * 1000

‘in re of Annual Interest Rate, clicking the scroll arrow will increment rate by 0.1% and clicking between a scroll arrow and the scroll box will increment rate by 1%:

rngScrlBar2.Offset(0, -1).Value = ScrollBar2.Value / 10

‘in re of Loan Tenure, clicking the scroll arrow will increment year by 0.5 and clicking between a scroll arrow and the scroll box will increment year by 2:

rngScrlBar3.Offset(0, -1).Value = ScrollBar3.Value / 2

If Not rngScrlBar1.Offset(0, -1).Value > 0 Then

MsgBox «Please Enter Loan Amount!»

Exit Sub

ElseIf Not rngScrlBar2.Offset(0, -1).Value > 0 Then

MsgBox «Please Enter Annual Interest Rate!»

Exit Sub

ElseIf Not rngScrlBar3.Offset(0, -1).Value > 0 Then

MsgBox «Please Enter Loan Tenure!»

Exit Sub

End If

‘calculate monthly instalment in cell B5:

rngScrlBar3.Offset(1, -1).Value = Pmt((rngScrlBar2.Offset(0, -1).Value / 100) / 12, rngScrlBar3.Offset(0, -1).Value * 12, rngScrlBar1.Offset(0, -1).Value) * -1

End Sub

Example: Form Control SpinButton (Spinner) & Macro to which it is assigned:

Create an Excel Form Control (Spinner) & set Spinner properties — use Shapes.AddFormControl Method to create an Excel Form Control which returns a Shape object representing the new control — Refer Image 9a

Sub FormControl_SpinButton_Shape_Properties()
‘use Shapes.AddFormControl Method to create an Excel Form Control (Spin Button) — this returns a Shape object representing the new control — SpinButton control enables to change (increment or decrement) value in a worksheet range — refer Image 9a.
‘refer Worksheet_Calculate macro — use the Calculate event to trap a sheet recalculation (viz. change in spinner value) so that clicking up / down the scroll arrow moves the active cell content one up / one down, in the worksheet column D

Dim ws As Worksheet, rngSpinBtn As Range, shpSpinBtn As Shape, objSpinBtn As OLEObject

Set ws = Sheets(«Sheet1»)

ws.Activate

‘set range/cell for SpinButton

Set rngSpinBtn = Range(«B2»)

‘delete ActiveX Control SpinButton objects

For Each objSpinBtn In ActiveSheet.OLEObjects

‘TypeName Function returns the data-type about a variable — TypeName(varname)

If TypeName(objSpinBtn.Object) = «SpinButton» Then objSpinBtn.Delete

Next objSpinBtn

‘delete Form Control SpinButton objects

For Each shpSpinBtn In ActiveSheet.Shapes

If shpSpinBtn.Type = msoFormControl Then

If shpSpinBtn.FormControlType = xlSpinner Then shpSpinBtn.Delete

End If

Next shpSpinBtn

rngSpinBtn.ColumnWidth = 3

rngSpinBtn.RowHeight = 24

‘for an already existing Form Control shape — SpinButton, with the name «Spinner 1»

‘Set shpSpinBtn = ws.Shapes(«Spinner 1»)

‘set object variable to the newly added SpinButton Form control — position & size the Spin Button with the cell assigned to the rngSpinBtn variable

‘use Shapes.AddFormControl Method to create an Excel Form Control — this returns a Shape object representing the new control — Syntax: Shapes.AddFormControl(Type, Left, Top, Width, Height):

‘a scroll bar gets oriented (horizontal or vertical) based on its size on the worksheet, whereas an ActiveX SpinButton has an Orientation property which can be set to be Auto, Horizontal, or Vertical

Set shpSpinBtn = ws.Shapes.AddFormControl(xlSpinner, Left:=rngSpinBtn.Left, Top:=rngSpinBtn.Top, Width:=rngSpinBtn.Width, Height:=rngSpinBtn.Height)

With shpSpinBtn

‘set a String value as object’s name

.Name = «Spinner 1«

‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)

.Placement = xlFreeFloating

‘use the Locked Property of the Shapes object to lock it — if not Locked (False), the object can be modified when the sheet is protected

.Locked = True

‘shape will retain its original proportions when it is resized

.LockAspectRatio = msoTrue

‘set the alternative text to a shape description when Shape object is saved to a Web page — alternative text may be displayed in the web browser in lieu of the shape’s image, or over the shape’s image when the mouse pointer hovers over the image (if browser supported).

.AlternativeText = «Spin«

‘ControlFormat property of the Shape object returns a ControlFormat object that contains Microsoft Excel control properties — the ControlFormat property will fail if the shape is not a control.

With .ControlFormat

.Enabled = True

‘spinner will be printed when the document is printed

.PrintObject = True

‘LinkedCell Property specifies a cell to set or store the Value property ie. the current value corresponding to the position of the spinner — changing the value of the control will automatically update the linked cell & a change in the linked cell will update the value of the control.

.linkedCell = rngSpinBtn.Address

‘specify the minimum and maximum acceptable values (as integer) of the SpinButton control (for the Value property setting)

.Min = 1

.Max = 100

‘SmallChange Property specifies the incremental change, as an integer value, that occurs when a user clicks the scroll arrow. Default value is 1.

.SmallChange = 1

‘Value property sets the control’s current value, which is an integer between maximum & minimum values specified in the Max and Min properties

.Value = 10

End With

End With

End Sub

Macro associated with the Calculate event of the Spinner: this Event-handler procedure must be located in the code module of the object worksheet containing the control (Spinner 1)

Private Sub Worksheet_Calculate()
‘Worksheet.Change Event is triggered when cells on the worksheet are changed by the user or by an external link — use the Calculate event to trap a sheet recalculation (viz. change in spinner value) — clicking up / down the scroll arrow moves the active cell content one up / one down, in the worksheet column D

Application.EnableEvents = False

On Error GoTo ErrorHandler

‘if active cell is not in column D, then exit procedure

If Application.Intersect(ActiveCell, Range(«D:D»)) Is Nothing Then GoTo ErrorHandler

Static PrevValue As Variant

Dim rng As Range

Dim strSpinDir As String

Dim str1 As String, str2 As String

Set rng = ActiveCell

If Shapes(«Spinner 1»).ControlFormat.Value < PrevValue Then

MsgBox «SpinDown»

str1 = rng.Value

str2 = rng.Offset(1, 0)

rng.Value = str2

rng.Offset(1, 0) = str1

rng.Offset(1, 0).Select

ElseIf Shapes(«Spinner 1»).ControlFormat.Value > PrevValue Then

‘if active cell is D1, then exit procedure

If Not Application.Intersect(ActiveCell, Range(«D1»)) Is Nothing Then

Shapes(«Spinner 1»).ControlFormat.Value = 10

PrevValue = Shapes(«Spinner 1»).ControlFormat.Value

GoTo ErrorHandler

End If

MsgBox «SpinUp»

str1 = rng.Value

str2 = rng.Offset(-1, 0)

rng.Value = str2

rng.Offset(-1, 0) = str1

rng.Offset(-1, 0).Select

End If

‘set spin button value, in variance from its Min or Max

Shapes(«Spinner 1»).ControlFormat.Value = 10

PrevValue = Shapes(«Spinner 1»).ControlFormat.Value

Application.EnableEvents = True

ErrorHandler:

Application.EnableEvents = True

End Sub

Example: ActiveX Control SpinButton & Macros associated with the events of the SpinDown & SpinUp ie. clicking down / up the scroll arrow: 

Add a new OLEObject to a sheet — ActiveX control (SpinButton) — set its properties by using the properties of an OLEObject object, & by using the Object property of the OLEObject object — Refer Image 9b

Sub ActiveXControl_SpinButton_OLEobject_Properties()
‘add a new OLEObject to a sheet — ActiveX control (SpinButton) — set its properties by using the properties of an OLEObject object, & by using the Object property of the OLEObject object — refer Image 9b
‘refer event handler procedures of SpinButton1_SpinDown & SpinButton1_SpinUp, associated with the events of the SpinDown & SpinUp ie. clicking down / up the scroll arrow.

Dim ws As Worksheet, rngSpinBtn As Range

‘OLEObject is not used for Form Controls

Dim objSpinBtn As OLEObject

Set ws = Sheets(«Sheet1»)

ws.Activate

‘set range/cell for SpinButton

Set rngSpinBtn = Range(«B2»)

‘delete ActiveX Control SpinButton objects

For Each objSpinBtn In ActiveSheet.OLEObjects

‘TypeName Function returns the data-type about a variable — TypeName(varname)

If TypeName(objSpinBtn.Object) = «SpinButton» Then objSpinBtn.Delete

Next objSpinBtn

rngSpinBtn.ColumnWidth = 3

rngSpinBtn.RowHeight = 24

‘for an already existing ActiveX control SpinButton, with the name «SpinButton1»

‘Set objSpinBtn = ws.OLEObjects(«SpinButton1»)

‘set object variable to the newly added SpinButton ActiveX control — position & size the SpinButton with the cell assigned to the rngSpinBtn variable

Set objSpinBtn = ws.OLEObjects.Add(ClassType:=»Forms.SpinButton.1«, DisplayAsIcon:=False, Left:=rngSpinBtn.Left, Top:=rngSpinBtn.Top, Width:=rngSpinBtn.Width, Height:=rngSpinBtn.Height)

With objSpinBtn

‘set a String value as object’s name

.Name = «SpinButton1«

‘no shadow

.Shadow = False

‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)

.Placement = xlFreeFloating

‘use the Locked Property of the Shapes object to lock it — if not Locked (False), the object can be modified when the sheet is protected

.Locked = True

.Enabled = True

‘SpinButton will be printed when the document is printed

.PrintObject = True

‘LinkedCell Property specifies a cell to set or store the Value property — changing the value of the control will automatically update the linked cell & a change in the linked cell will update the value of the control.

‘set no linked cell

.linkedCell = ««

‘if the property is not listed under the OLEObject class in the Object Browser, then you must return the actual control object by using the Object property of the OLEObject object

‘Object Property of the OLEObject returns a OLE Automation object associated with this OLE object

With .Object

‘specify the minimum and maximum acceptable values (as integer) of the SpinButton control (for the Value property setting)

.Min = 1

.Max = 100

‘Orientation Property determines a vertical SpinButton or a horizontal SpinButton. It has 3 settings: (i) fmOrientationAuto (Value -1, default) — SpinButton dimensions automatically determine whether the SpinButton is Vertical or Horizontal. Where width is more than height, SpinButton is Horizontal and where height is more than width, SpinButton is Vertical; (ii) FmOrientationVertical (Value 0) — vertical SpinButton; and (iii) FmOrientationHorizontal (Value 1) — horizontal SpinButton.

.Orientation = fmOrientationVertical

‘SmallChange Property specifies the incremental change, as an integer value, that occurs when a user clicks the scroll arrow. Default value is 1.

.SmallChange = 1

‘Value property sets the control’s current value, which is an integer between maximum & minimum values specified in the Max and Min properties

.Value = 1

‘specify type of mouse pointer

.MousePointer = fmMousePointerArrow

‘set background color to yellow

.BackColor = RGB(255, 255, 0)

‘set scroll arrow color to red

.ForeColor = RGB(255, 0, 0)

End With

End With

End Sub

Macro associated with the event of SpinDown ie. clicking down the scroll arrow of SpinButton1: this Event-handler procedure must be located in the code module of the object worksheet containing the control (SpinButton1)

Private Sub SpinButton1_SpinDown()
‘clicking down the scroll arrow moves the active cell content one down in the worksheet column D

On Error Resume Next

‘if active cell is not in column D, then exit procedure

If Application.Intersect(ActiveCell, Range(«D:D»)) Is Nothing Then Exit Sub

‘spin button value remains constant

SpinButton1.Value = 1

Dim rng As Range, str1 As String, str2 As String

Set rng = ActiveCell

str1 = rng.Value

str2 = rng.Offset(1, 0)

rng.Value = str2

rng.Offset(1, 0) = str1

rng.Offset(1, 0).Select

End Sub

Macro associated with the event of SpinUp ie. clicking up the scroll arrow of SpinButton1: this Event-handler procedure must be located in the code module of the object worksheet containing the control (SpinButton1)

Private Sub SpinButton1_SpinUp()
‘clicking up the scroll arrow moves the active cell content one up in the worksheet column D

On Error Resume Next

‘if active cell is not in column D, then exit procedure

If Application.Intersect(ActiveCell, Range(«D:D»)) Is Nothing Then Exit Sub

‘if active cell is D1, then exit procedure

If Not Application.Intersect(ActiveCell, Range(«D1»)) Is Nothing Then Exit Sub

‘spin button value remains constant

SpinButton1.Value = 1

Dim rng As Range, str1 As String, str2 As String

Set rng = ActiveCell

str1 = rng.Value

str2 = rng.Offset(-1, 0)

rng.Value = str2

rng.Offset(-1, 0) = str1

rng.Offset(-1, 0).Select

End Sub

TextBox — ActiveX Control

A TextBox is a rectangular box, wherein you may type, edit or view text or data, or it may also be a static text field displaying read-only information. Below we illustrate an ActiveX Control TextBox & Macro associated with the GotFocus event of the TextBox.

Example: ActiveX Control TextBox & Macro associated with the GotFocus event of the TextBox:

Add a new OLEObject to a sheet — ActiveX control (TextBox) — set its properties by using the properties of an OLEObject object, & by using the Object property of the OLEObject object — Refer Image 10a

Sub ActiveXControl_TextBox_OLEobject_Properties()
‘add a new OLEObject to a sheet — ActiveX control (TextBox) — set its properties by using the properties of an OLEObject object, & by using the Object property of the OLEObject object — refer Image 10a

Dim ws As Worksheet, rng As Range

‘OLEObject is not used for Form Controls

Dim objTB As OLEObject

Set ws = Sheets(«Sheet1»)

ws.Activate

Set rng = ws.Range(«A11»)

‘delete ActiveX Control ScrollBar objects

For Each objTB In ActiveSheet.OLEObjects

‘TypeName Function returns the data-type about a variable — TypeName(varname)

If TypeName(objTB.Object) = «TextBox» Then objTB.Delete

Next objTB

‘for an already existing ActiveX control checkbox, with the name «TextBox1»

‘Set objTB = ws.OLEObjects(«TextBox1»)

‘set object variable to the newly added check box ActiveX control — position the check box with the cell assigned to the rng variable

Set objTB = ws.OLEObjects.Add(ClassType:=»Forms.TextBox.1«, DisplayAsIcon:=False, Left:=rng.Left, Top:=rng.Top, Width:=150, Height:=40)

With objTB

‘set a String value as object’s name

.Name = «TextBox1«

‘set shadow

.Shadow = False

‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)

.Placement = xlFreeFloating

‘use the Locked Property of the Shapes object to lock it — if not Locked (False), the object can be modified when the sheet is protected

.Locked = True

‘Enabled Property of a TextBox should be set to False if you do not want to allow the user to type directly into the TextBox which should be filled only per the user-selected option, say from a ListBox

.Enabled = True

‘TextBox will be printed when the document is printed

.PrintObject = True

‘the text or value in the TextBox will get stored in this worksheet cell

.linkedCell = rng.Offset(-2, 0).Address

‘wrt to the cell which is under the upper-left corner of the textbox

MsgBox .TopLeftCell.Address

‘wrt to the cell which is under the lower-right corner of the textbox

MsgBox .BottomRightCell.Address

‘if the property is not listed under the OLEObject class in the Object Browser, then you must return the actual control object by using the Object property of the OLEObject object

‘Object Property of the OLEObject returns a OLE Automation object associated with this OLE object

With .Object

‘enabling the DragBehavior property enables the drag-and-drop feature for TextBox — dragging in text box starts a drag-and-drop operation on the selected text

.DragBehavior = fmDragBehaviorEnabled

‘EnterKeyBehavior Property: A Boolean value (True/False) which determines the effect when a user presses the ENTER key in a TextBox. If MultiLine property is set to True, then the True value indicates creating a new line on pressing ENTER while the False value (Default) moves focus to the next control in the tab order. If MultiLine property is set to False, then focus is always moved to the next control in the tab order ignoring the EnterKeyBehavior Property.

.EnterKeyBehavior = True

‘if MultiLine is True, set TabKeyBehavior property to True whereby pressing ENTER inserts a Tab and set to False (default) whereby pressing ENTER moves the focus to the next object in the tab order; If MultiLine is False, pressing ENTER will always move the focus to the next control in the tab order.

.TabKeyBehavior = True

‘set SelectionMargin property to True: selection margin occupies a thin strip along the left edge of the control’s edit region, & set to False for the entire edit region to store text.

.SelectionMargin = False

.MultiLine = True

‘caption text will wrap to the next line

.WordWrap = True

‘AutoSize setting for TextBox: (i) if the TextBox is single-line, AutoSize resizes width of TextBox to the length of the text; (ii) if the TextBox is MultiLine with no text, AutoSize resizes width to display single letter (of widest width of that font size) and resizes height to display the entire text; and (iii) if the TextBox is MultiLine with text present, AutoSize does not change the width of the TextBox and resizes height to display the entire text.

.AutoSize = False

‘ScrollBars Property: Specifies whether a TextBox has vertical and/or horizontal scroll bars, or none. There are 4 self-explanatory settings: (i) fmScrollBarsNone (value 0) — default; (ii) fmScrollBarsHorizontal (value 1); (iii) fmScrollBarsVertical (value 2); and (iv) fmScrollBarsBoth (value 3). The scroll bar setting fmScrollBarsNone displays no scroll bar. If AutoSize is set to True, no scroll bar is diplayed because the TextBox enlarges itself to accommodate the additional text or data. If WordWrap is set to True, a multiline TexBox displays no horizontal scroll bar. The scroll bar settings fmScrollBarsHorizontal or fmScrollBarsBoth, display a horizontal scroll bar in a singleline TextBox if the text is longer than the edit region. The scroll bar settings fmScrollBarsVertical or fmScrollBarsBoth, display a vertical scroll bar in a multiline TextBox if the text is longer than the edit region and WordWrap is set to True. To display a horizontal scroll bar in a multiline TexBox, the scroll bar setting should be fmScrollBarsHorizontal, WordWrap should be set to False and the text should be longer than the edit region. Note 1: A horizontal (or vertical) scroll bar is visible only if the control has enough room to include the scroll bar under (or at the right edge of) its edit region.

.ScrollBars = 2

‘text alignment set to center

.TextAlign = fmTextAlignCenter

‘specify characters displayed in TextBox instead of the characters actually entered

‘.PasswordChar = «*«

‘MaxLength property specifies the maximum number of characters which can be entered by the user in a TextBox — set maximum length for password field

‘.MaxLength = 5

‘use the Text property to set text in a TextBox — a value assigned to the Text property gets automatically assigned to the Value property, and vice-versa.

.Text = «Hello»

‘determines how the control visually appears

.SpecialEffect = fmButtonEffectFlat

‘specify type of mouse pointer

.MousePointer = fmMousePointerArrow

‘set the background color for control to yellow

.BackColor = RGB(255, 255, 0)

‘set font color to red

.ForeColor = RGB(255, 0, 0)

‘set background to be Opaque or Transparent — BackStyle property should be set to fmBackStyleOpaque for the BackColor to have any effect

.BackStyle = fmBackStyleOpaque

‘set border

.BorderStyle = fmBorderStyleSingle

.BorderColor = vbBlue

With .Font

.Name = «Arial«

.Bold = True

.Size = 10

.Italic = False

.Underline = False

End With

End With

End With

End Sub

Macro associated with the GotFocus event of the TextBox: this Event-handler procedure must be located in the code module of the object worksheet containing the control (TextBox1) — refer Image 10b.

Private Sub TextBox1_GotFocus()
‘if the active cell is in the worksheet column A (except cell A1), then focus on the TextBox (ex. selecting the TextBox) will set text in the TextBox — refer Image 10b (selecting Jack in column A & then selecting TextBox)

On Error Resume Next

‘if active cell is not in column A, then exit procedure

If Application.Intersect(ActiveCell, Range(«A:A»)) Is Nothing Then Exit Sub

‘if active cell is A1, then exit procedure

If Not Application.Intersect(ActiveCell, Range(«A1»)) Is Nothing Then Exit Sub

If ActiveCell.Value <> «» Then

TextBox1.Text = ActiveCell.Value & «‘s height is » & ActiveCell.Offset(0, 1).Value & » cms & weight is » & ActiveCell.Offset(0, 2).Value & » kg»

End If

End Sub

Label — Form Control or ActiveX Control

Label stores text which is not editable by user, and is used to describe other controls (often a TextBox) or purpose of a worksheet cell or to provide instructions — you may display any descriptive text like caption, title or pictures in a Label.

Below we illustrate: (i) a Form Control Label; and (ii) an ActiveX Control Label.

Example: Form Control Label:

Create an Excel Form Control (Label) & set its properties — use Shapes.AddFormControl Method to create an Excel Form Control which returns a Shape object representing the new control

Sub FormControl_Label_Shape_Properties()
‘use Shapes.AddFormControl Method to create an Excel Form Control (Label) — this returns a Shape object representing the new control

Dim ws As Worksheet, rngLbl As Range, shpLbl As Shape, objLbl As OLEObject

Set ws = Sheets(«Sheet1»)

ws.Activate

‘set range/cell for Label

Set rngLbl = Range(«E15»)

‘delete ActiveX Control Label objects

For Each objLbl In ActiveSheet.OLEObjects

‘TypeName Function returns the data-type about a variable — TypeName(varname)

If TypeName(objLbl.Object) = «Label» Then objLbl.Delete

Next objLbl

‘delete Form Control Label objects

For Each shpLbl In ActiveSheet.Shapes

If shpLbl.Type = msoFormControl Then

If shpLbl.FormControlType = xlLabel Then shpLbl.Delete

End If

Next shpLbl

rngLbl.ColumnWidth = 10

rngLbl.RowHeight = 18

‘for an already existing Form Control Label, with the name «Label 1»

‘Set shpLbl = ws.Shapes(«Label 1»)

‘set object variable to the newly added Label Form control — position & size the Label with the cell assigned to the rngSpinBtn variable

‘use Shapes.AddFormControl Method to create an Excel Form Control — this returns a Shape object representing the new control — Syntax: Shapes.AddFormControl(Type, Left, Top, Width, Height):

Set shpLbl = ws.Shapes.AddFormControl(xlLabel, Left:=rngLbl.Left, Top:=rngLbl.Top, Width:=rngLbl.Width, Height:=rngLbl.Height)

With shpLbl

‘set a String value as object’s name

.Name = «Label 1«

‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)

.Placement = xlFreeFloating

‘use the Locked Property of the Shapes object to lock it — if not Locked (False), the object can be modified when the sheet is protected

.Locked = True

‘shape will retain its original proportions when it is resized

.LockAspectRatio = msoTrue

‘set the alternative text to a shape description when Shape object is saved to a Web page — alternative text may be displayed in the web browser in lieu of the shape’s image, or over the shape’s image when the mouse pointer hovers over the image (if browser supported).

.AlternativeText = «Label1«

‘use the Caption property to display text

.OLEFormat.Object.Caption = «Country«

‘alternatively:

‘TextFrame Property returns a TextFrame object which contains the alignment & anchoring properties for a shape — valid for only a shape having a text frame

.TextFrame.Characters.Text = «USA«

‘ControlFormat property of the Shape object returns a ControlFormat object that contains Microsoft Excel control properties — the ControlFormat property will fail if the shape is not a control.

With .ControlFormat

.Enabled = True

‘label will be printed when the document is printed

.PrintObject = True

End With

End With

End Sub

Example: ActiveX Control Label:

Add a new OLEObject to a sheet — ActiveX control (Label) — set its properties by using the properties of an OLEObject object, & by using the Object property of the OLEObject object — Refer Image 11.

Sub ActiveXControl_Label_OLEobject_Properties()
‘add a new OLEObject to a sheet — ActiveX control (Label) — set its properties by using the properties of an OLEObject object, & by using the Object property of the OLEObject object — Refer Image 11
‘Label stores text which is not editable by user, and is used to describe other controls — in the Image, Labels are in Green color & describe OptionButtons to their right.

Dim ws As Worksheet, rng As Range

‘OLEObject is not used for Form Controls

Dim objLbl As OLEObject

Set ws = Sheets(«Sheet11»)

ws.Activate

Set rng = Union(Range(«A5»), Range(«A6»))

‘delete ActiveX Control Label objects

For Each objLbl In ActiveSheet.OLEObjects

‘TypeName Function returns the data-type about a variable — TypeName(varname)

If TypeName(objLbl.Object) = «Label» Then objLbl.Delete

Next objLbl

‘for an already existing ActiveX control Label, with the name «Label1»

‘Set objLbl = ws.OLEObjects(«Label1»)

‘set object variable to the newly added Label ActiveX control — position the Label with the cell assigned to the rng variable

Set objLbl = ws.OLEObjects.Add(ClassType:=»Forms.Label.1″, DisplayAsIcon:=False, Left:=rng.Left, Top:=rng.Top, Width:=rng.Width, Height:=rng.Height)

With objLbl

‘set a String value as object’s name

.Name = «Label1«

.Shadow = True

‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)

.Placement = xlFreeFloating

‘use the Locked Property of the Shapes object to lock it — if not Locked (False), the object can be modified when the sheet is protected

.Locked = True

.Enabled = True

‘label will be printed when the document is printed

.PrintObject = True

‘if the property is not listed under the OLEObject class in the Object Browser, then you must return the actual control object by using the Object property of the OLEObject object

‘Object Property of the OLEObject returns a OLE Automation object associated with this OLE object

With .Object

‘text alignment (horizontal) set to center — note there is no specific property to vertically align text within a label

.TextAlign = fmTextAlignCenter

‘use the Caption property to display text

.Caption = «Europe«

‘determines how the control visually appears

.SpecialEffect = fmButtonEffectFlat

‘specify type of mouse pointer

.MousePointer = fmMousePointerArrow

‘caption text will wrap to the next line

.WordWrap = True

‘setting AutoSize to True automatically resizes the Caption while False (Default option) keeps the caption size constant wherein content exceeding the control area gets cut.

.AutoSize = False

‘set the background color for control to green

.BackColor = RGB(0, 255, 0)

‘set font color to black

.ForeColor = RGB(0, 0, 0)

‘set background to be Opaque or Transparent — BackStyle property should be set to fmBackStyleOpaque for the BackColor to have any effect

.BackStyle = fmBackStyleOpaque

‘set border

.BorderStyle = fmBorderStyleSingle

‘set border color

.BorderColor = vbBlue

With .Font

.Name = «Arial«

.Bold = True

.Size = 8

.Italic = False

.Underline = False

End With

End With

End With

‘copy Label1 to clipboard

ws.OLEObjects(«Label1»).Copy

‘paste a copy of the Label in the same sheet

ws.Paste

‘position new Label

Selection.Left = Range(«A2»).Left

Selection.Top = Range(«A2»).Top

Selection.Name = «Label2»

ws.OLEObjects(«Label2»).Object.Caption = «America«

End Sub

Illustrating Auto Shapes, Add a connector

Example: Illustrating Auto Shapes, add a connector — refer Image 12  — use the Shapes.AddShape Method to Add  a new AutoShape — this returns a Shape object that representing the new AutoShape

Sub AutoShapes_Shape_Properties()
‘illustrating Auto Shapes, add a connector — refer Image 12
‘Use the Shapes.AddShape Method to Add  a new AutoShape — this returns a Shape object that representing the new AutoShape — Syntax: Shapes.AddShape(Type, Left, Top, Width, Height). The Type argument specifies the shape type per the MsoAutoShapeType Enumeration

Dim ws As Worksheet

Dim shp As Shape, shpRectangle As Shape, shpTriangle As Shape, shpOval As Shape, shpRightArrow As Shape, shpConn As Shape

Dim rngRectangle As Range, rngTriangle As Range, rngOval As Range, rngRightArrow As Range

Set ws = Sheets(«Sheet1»)

‘———————————

‘delete all auto shapes

For Each shp In ws.Shapes

If shp.Type = msoAutoShape Then

‘MsgBox shp.Name & «, » & shp.AutoShapeType

shp.Delete

End If

Next

‘———————————

‘add 4 shapes in worksheet — Rectangle, Triangle, Oval & Right Arrow:

‘set range/cell for ToggleButton

Set rngRectangle = Range(«B3»)

Set rngTriangle = rngRectangle.Offset(2, 0)

Set rngOval = rngRectangle.Offset(4, 0)

Set rngRightArrow = rngRectangle.Offset(6, 0)

‘Range.ColumnWidth Property returns or sets the width of all columns in the specified range, where one unit of column width is equal to the width of one character in the Normal style (width of the character zero is used for proportional fonts) — to return (does not set) the width of the range in points, use the Range.Width property

rngRectangle.ColumnWidth = 18

‘Range.RowHeight Property returns or sets the height of the first row in the range, in points — to set or return the total height of a range of cells in points, use the Height property.

rngRectangle.RowHeight = 24

rngTriangle.RowHeight = 36

rngOval.RowHeight = 55

rngRightArrow.RowHeight = 18

‘for an already existing ActiveX control ToggleButton, with the name «ToggleButton1»

‘Set shpRectangle = ws.shapes(«Rectangle 1»)

‘set object variable to the newly added ToggleButton ActiveX control — position & size the Rectangle with the cell assigned to the rngRectangle variable

Set shpRectangle = ws.Shapes.AddShape(Type:=msoShapeRectangle, Left:=rngRectangle.Left, Top:=rngRectangle.Top, Width:=rngRectangle.Width, Height:=rngRectangle.Height)

shpRectangle.Name = «Rectangle 1«

Set shpTriangle = ws.Shapes.AddShape(Type:=msoShapeIsoscelesTriangle, Left:=rngTriangle.Left, Top:=rngTriangle.Top, Width:=rngTriangle.Width, Height:=rngTriangle.Height)

shpTriangle.Name = «Triangle 1«

Set shpOval = ws.Shapes.AddShape(Type:=msoShapeOval, Left:=rngOval.Left, Top:=rngOval.Top, Width:=rngOval.Width, Height:=rngOval.Height)

shpOval.Name = «Oval 1«

Set shpRightArrow = ws.Shapes.AddShape(Type:=msoShapeRightArrow, Left:=rngRightArrow.Left, Top:=rngRightArrow.Top, Width:=30, Height:=rngRightArrow.Height)

shpRightArrow.Name = «Right Arrow 1«

‘refer Shapes collection ie. Shapes object

‘returns 4 (there are four shapes in the collection)

MsgBox ws.Shapes.Count

‘———————————

‘set some common properties for all shapes

‘refer each Shape object

For Each shp In ws.Shapes

‘shape will retain its original proportions when it is resized

shp.LockAspectRatio = msoTrue

‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)

shp.Placement = xlFreeFloating

‘use the Locked Property of the Shapes object to lock it — if not Locked (False), the object can be modified when the sheet is protected

shp.Locked = True

‘MsgBox shp.Name

‘shape will be printed when the document is printed

shp.OLEFormat.Object.PrintObject = True

Next shp

‘———————————

‘set properties for Rectangle shape

With shpRectangle

‘indicates the ThreeDFormat object is visible

.ThreeD.Visible = msoTrue

‘use the BevelTopType Property of the ThreeDFormat object to set the type of top bevel, as per the constants defined in MsoBevelType Enumeration: msoBevelCircle, msoBevelSlope, msoBevelSoftRound, msoBevelConvex, …

.ThreeD.BevelTopType = msoBevelCircle

‘set the width & height of the bevel using the BevelTopInset & BevelTopWidth values respectively — this means setting the width & height of the raised edge at the top of a shape

‘set width to 10 points

.ThreeD.BevelTopInset = 10

‘set height to 5 points

.ThreeD.BevelTopDepth = 5

‘set the alternative text to a shape description when Shape object is saved to a Web page — alternative text may be displayed in the web browser in lieu of the shape’s image, or over the shape’s image when the mouse pointer hovers over the image (if browser supported).

.AlternativeText = .Name

‘set fill / interior

With .Fill

.Visible = msoTrue

.Solid

‘.ForeColor.SchemeColor = 13

.ForeColor.RGB = RGB(255, 255, 0)

.Transparency = 0

End With

‘set border

With .Line

‘.Weight = 1

.DashStyle = msoLineSolid

.Style = msoLineSingle

.Transparency = 0

‘.ForeColor.SchemeColor = 10

.ForeColor.RGB = RGB(0, 255, 0)

End With

‘set text

With .TextFrame

‘.HorizontalAlignment = xlHAlignCenter

.HorizontalAlignment = xlHAlignLeft

‘.VerticalAlignment = xlVAlignDistributed

.VerticalAlignment = xlVAlignCenter

.Characters.Text = «Rectangle«

With .Characters.Font

.Name = «Arial«

.ColorIndex = 5

.Size = 11

.Bold = True

.Italic = False

End With

.Characters(Start:=1, Length:=1).Font.ColorIndex = 3

End With

End With

‘———————————
‘set properties for Triangle shape

With shpTriangle

‘set the alternative text to a shape description when Shape object is saved to a Web page — alternative text may be displayed in the web browser in lieu of the shape’s image, or over the shape’s image when the mouse pointer hovers over the image (if browser supported).

‘shpTriangle.Name is «Triangle 1»

.AlternativeText = .Name

‘set fill / interior

With .Fill

.Visible = msoTrue

‘yellow

.ForeColor.SchemeColor = 13

.Transparency = 0.2

End With

‘set border

With .Line

‘to not display border, use msoFalse

.Visible = msoTrue

.Weight = 1

.DashStyle = msoLineDash

.Transparency = 0

.ForeColor.SchemeColor = 10

End With

‘set text to display caption — first 8 letters of shpTriangle.Name

.OLEFormat.Object.Caption = Left(shpTriangle.Name, 8)

With .OLEFormat.Object.Font

.Name = «Arial«

.Bold = True

.Size = 8

.Italic = False

.ColorIndex = 5

End With

.OLEFormat.Object.Shadow = True

With .Shadow

‘use the Style Property of the ShadowFormat object to set the type of shadowing effect, as per the style constants defined in the MsoShadowStyle Enumeration

.Style = msoShadowStyleOuterShadow

‘use the ForeColor Property of the ShadowFormat object to set the fill color for the shadow

.ForeColor.RGB = RGB(255, 0, 0)

.Blur = 2

‘use the Size Property of the ShadowFormat object to set a value representing the percentage size for the shadow

.Size = 90

‘the OffsetX Property of the ShadowFormat object sets a value, in points, indicating the horizontal offset of the shadow to the chart area, with a negative value offsetting the shadow to the left

.OffsetX = 6

‘the OffsetY Property of the ShadowFormat object sets a value, in points, indicating the vertical offset of the shadow to the chart area, with a negative value offsetting the shadow to the above

.OffsetY = -5

‘the Transparency Property of the ShadowFormat object sets the degree of the transparency in a fill, as a value from 0.0 (opaque) to 1.0 (clear), for solid color fills

.Transparency = 0.2

End With

End With

‘———————————

‘Oval shape: set an image to the specified fill

With shpOval.Fill

‘using the ChartFillFormat.UserPicture Method to fill the shape with an image — specify filename & path of image file

.UserPicture «C:UsersamitDocumentsPhotosDollar.jpg»

End With

‘———————————

‘Right Arrow shape:

With shpRightArrow

.Fill.ForeColor.RGB = RGB(0, 0, 255)

.ThreeD.BevelTopType = msoBevelConvex

‘to not display border, use msoFalse

.Line.Visible = msoFalse

‘use the Shape.OnAction Property to assign a macro (ie. sets the macro name) to the shape — clicking on shpRightArrow will execute the NextStep macro

.OnAction = «NextStep«

End With

‘———————————

‘add the connector in 5 steps:

‘To add a connector: 1) Add a connector shape; 2) specify the shape it begins at; 3) specify the shape it ends at; 4) reroute the connector given the position of the 2 shapes which it links; 5) format the connector;

‘use the Shapes.AddConnector Method to create a connector — this method returns a Shape object representing the new connector. Syntax: Shapes.AddConnector(Type, BeginX, BeginY, EndX, EndY) — use the Type argument to specify the connectr type (msoConnectorCurve, msoConnectorElbow, msoConnectorStraight). The BeginX & EndX arguments specify the horizontal position (in points) of the start & end points relative to the upper-left corner of the document & the BeginY & EndY arguments specify the vertical position (in points) of the start & end points relative to the upper-left corner of the document. All arguments are necessary to specify.

‘The new connector added does not connect anything — you will need to use the BeginConnect & EndConnect methods to specify shapes where the connector begins & ends at.

‘add the connector (curved connector) without regard to its position or size as it will be redrawn later.

Set shpConn = ws.Shapes.AddConnector(msoConnectorCurve, 1, 1, 1, 1)

Dim iLastSite As Integer

iLastSite = shpOval.ConnectionSiteCount

With shpConn

‘use the ConnectorFormat.BeginConnect Method to attach the beginning of the connector to a shape — Syntax: ConnectorFormat.BeginConnect(ConnectedShape, ConnectionSite) — the ConnectedShape argument specifies the shape to which the beginning of the connector is attached to. The ConnectionSite argument specifies the number (Integer) of the connection site on the shape between 1 and the number of connection sites on a shape (which can be returned by using the Shape.ConnectionSiteCount Property).

‘attach the beginning of the connector to connection site 2 on the shpTriangle & the attach the connector end to the last connection site of the shpOval

.ConnectorFormat.BeginConnect shpTriangle, 2

‘use the ConnectorFormat.EndConnect Method to attach the end of the connector to a shape

.ConnectorFormat.EndConnect shpOval, iLastSite

‘use the ShapeRange.RerouteConnections Method to reroute the connector so as to take the shortest possible path between the shapes it connects, and for this the ends of a connector may be reattached to different connecting sites on the connected shapes.

‘.RerouteConnections

‘format the connector — set color to red & thickness to 2 pts

.Line.ForeColor.RGB = RGB(255, 0, 0)

.Line.Weight = 2

End With

End Sub

В настоящей заметке рассматриваются методы создания пользовательских форм и работы с ними.[1] Пользовательские диалоговые окна создаются на основе технологии пользовательских форм, к которым можно получить доступ из редактора Visual Basic (VBE; подробнее см. Настройка среды Visual Basic Editor).

Рис. 1. Окно новой пустой формы UserForm

Скачать заметку в формате Word или pdf, примеры в формате архива

Стандартная последовательность шагов при этом следующая:

  1. Вставьте новую форму UserForm в проект VBAProject рабочей книги.
  2. Добавьте элементы управления в форму UserForm.
  3. Настройте свойства добавленных элементов управления.
  4. Создайте процедуры «обработчики событий» для элементов управления. Эти процедуры добавляются в модуль кода UserForm и выполняются при возникновении различных событий (например, при щелчке на кнопке).
  5. Разработайте процедуру, которая отображает форму UserForm. Эта процедура находится в модуле VBA (а не в модуле кода для формы UserForm).
  6. Определите простой способ вызова на выполнение процедуры, созданной в п. 5. Можно поместить кнопку на рабочий лист, команду ленты и т.д.

Рассмотрим эти шаги подробнее.

Вставка новой формы UserForm

Чтобы добавить в проект форму UserForm, запустите VBE (например, нажав в Excel клавиши <Alt+F11>), выберите рабочую книгу в окне Project и выполните команду Inserts –> UserForm). Формы UserForm получают такие имена, как UserForm1, UserForm2 и т.д. Можно переименовать форму, изменив свойство Name в окне Properties (см. рис. 1). Если это окно не отображается, нажмите в VBE клавишу <F4>. В рабочей книге может быть произвольное количество форм UserForm, а каждая форма включает единственное пользовательское диалоговое окно.

Добавление элементов управления в пользовательское диалоговое окно

Чтобы добавить элементы управления в форму UserForm, воспользуйтесь панелью Toolbox. Обратите внимание, что в VBE отсутствуют команды меню, предназначенные для добавления элементов управления. Если панель Toolbox не отображена на экране, пройдите по меню View –> Toolbox (рис. 2).

Рис. 2. Окно Toolbox для добавления элементов управления в пользовательскую форму

Щелкните на той кнопке в панели Toolbox, которая соответствует добавляемому элементу управления. После этого щелкните внутри диалогового окна для создания элемента управления (используется размер элемента по умолчанию). Также можно щелкнуть на элементе управления и, перетащив его границы в диалоговом окне, задать необходимый размер в пользовательском диалоговом окне. Добавленному элементу управления назначается имя, которое состоит из названия типа элемента управления и числового кода. Рекомендуется их переименовать, чтобы в коде VBA было понятно, с чем вы имеете дело. Согласитесь, что РrоductListBox звучит лучше, чем ListBox1.

Элементы управления в окне Toolbox

Форма UserForm, которая показана на рис. 3, размещена в файле all userform controls.xlsm.

Рис. 3. Эта форма UserForm содержит 15 элементов управления

Элемент управления CheckBox (6) предоставляет пользователю возможность выбрать один из двух вариантов: включить или выключить. Если галочка установлена, то CheckBox имеет значение True, в противном случае – False.

ComboBox (4) подобен объекту ListBox (5). Отличие заключается в том, что ComboBox представляет раскрывающийся список, в котором в определенный момент времени отображается только одно значение. Кроме того, пользователю в поле списка разрешено вводить значение, которое необязательно представляет одну из опций объекта ComboBox.

Каждое создаваемое диалоговое окно будет иметь как минимум один элемент управления CommandButton (10). Обычно используются кнопки ОК и Отмена.

Элемент управления Frame (9) применяется в качестве оболочки для других элементов управления. Он добавляется в диалоговое окно либо в целях эстетики, либо из соображений логического группирования однотипных элементов управления. Элемент управления Frame требуется в случае, если в диалоговом окне содержится более одного набора элементов управления OptionButton.

Элемент управления Image (15) используется для представления графического изображения, которое сохранено в отдельном файле или вставляется из буфера обмена. Графическое изображение сохраняется вместе с рабочей книгой. Таким образом, вместе с рабочей книгой передавать другому пользователю копию графического файла необязательно. Некоторые графические файлы занимают много места, поэтому их включение в рабочую книгу приведет к радикальному увеличению ее размера.

Элемент управления Label (2) отображает текст в диалоговом окне.

Элемент управления ListBox (5) предоставляет список опций, из которого пользователь может выбрать один вариант (или несколько). Вы вправе указать диапазон на листе, который содержит элементы списка. Этот диапазон может состоять из нескольких столбцов. Кроме того, элемент управления ListBox может заполняться с помощью кода VBA.

Элемент управления MultiPage (12) позволяет создавать диалоговые окна с несколькими вкладками, которые подобны появляющимся после выбора команды Формат ячеек. По умолчанию элемент управления MultiPage состоит из двух вкладок.

Элемент управления OptionButton (7) применяется при выборе пользователем одного варианта из нескольких. Эти элементы управления всегда группируются в диалоговом окне в наборы, содержащие не менее двух опций. Когда один элемент управления OptionButton выбран, все остальные элементы управления OptionButton текущей группы автоматически становятся неактивными. Если в пользовательском диалоговом окне содержится более одного набора элементов управления OptionButton, то каждый из таких наборов должен иметь собственное значение свойства GroupName. В противном случае все элементы управления OptionButton в диалоговом окне рассматриваются как члены одной группы. Также можно вставить элементы управления OptionButton в объект Frame, что приведет к их автоматическому группированию.

Элемент управления RefEdit (16) используется тогда, когда пользователь должен выделить диапазон ячеек на листе.

Элемент управления ScrollBar (13) в некотором смысле подобен элементу управления SpinButton. Разница заключается в том, что пользователь может перетаскивать ползунок объекта ScrollBar для изменения значения с большим приращением. Элемент управления ScrollBar рекомендуется использовать при выборе значения из большого диапазона.

Элемент управления SpinButton (14) позволяет выбрать значение после щелчка на одной из двух кнопок со стрелками. Одна из них применяется для увеличения значения, а вторая — для уменьшения. Элемент управления SpinButton часто используется совместно с элементами управления TextBox и Label, которые содержат текущее значение элемента управления SpinButton.

Элемент управления TabStrip (11) подобен элементу управления MultiPage, однако использовать его сложнее. Элемент управления TabStrip, в отличие от MultiPage, не выступает контейнером для других объектов. Как правило, элемент управления MultiPage обладает более широкими возможностями.

Элемент управления TextBox (3) позволяет пользователям вводить текст в диалоговом окне.

Элемент управления ToggleButton (8) имеет два состояния: включен и выключен. Щелчок на кнопке приводит к изменению состояния на противоположное и к изменению внешнего вида кнопки. Этот элемент управления может иметь значение True (активен) или False (неактивен). Он не относится к «стандартным» элементам управления, поэтому использование двух элементов управления OptionButton или одного CheckBox может оказаться более удачным вариантом.

Использование элементов управления на рабочем листе

Элементы управления пользовательскими диалоговыми окнами могут встраиваться в рабочий лист (без использования UserForm). Доступ к элементам управления можно получить, пройдя в Excel Разработчик –> Элементы управления –> Вставить. Для использования подобных элементов в составе рабочего листа требуется гораздо меньше усилий, чем для создания пользовательского диалогового окна. Кроме того, в данном случае можно не создавать макросы, поскольку элемент управления можно связать с ячейкой рабочего листа.

Например, если на рабочий лист вставить элемент управления CheckBox, его можно связать с нужной ячейкой, задав свойство LinkedCell. Если флажок установлен, в связанной ячейке отображается значение ИСТИНА. Если же флажок сброшен, то в связанной ячейке отображается значение ЛОЖЬ. Например, на рис. 4 переключатель «Фикс. Ставка 20%» связан с ячейкой Н15. Рисунок отображает рабочий лист, содержащий некоторые элементы управления ActiveX (см. файл activex worksheet controls.xlsx). Книга включает связанные ячейки и не содержит макросов.

Рис. 4. Элементы управления ActiveX без макросов

Элементы управления на рабочем листе могут происходить из двух источников:

  • Элементы управления формами. Эти элементы управления являются внедряемыми объектами.
  • Элементы управления ActiveX. Эти элементы управления являются подмножеством элементов, доступных в пользовательских диалоговых окнах.

Эти элементы управления работают не одинаково. После добавления элемента управления ActiveX в рабочий лист Excel переходит в режим конструктора. В этом режиме можно настраивать свойства любого элемента управления рабочего листа, добавлять или изменять процедуры обработки событий для элемента управления, а также изменять его размер или положение. Для отображения окна свойств элемента управления ActiveX воспользуйтесь командой Разработчик –> Элементы управления –> Свойства.

Для создания простых кнопок можно использовать элемент управления Button (Кнопка), который находится на панели инструментов Формы (Form). В этом случае обеспечивается возможность запуска макроса. Если же воспользоваться элементом управления CommandButton, который относится к группе элементов управления ActiveX, то после щелчка на нем вызывается связанная процедура обработки событий (например, CommandButton1_Click), которая находится в модуле кода объекта Лист (Sheet). Связать макрос с этой процедурой нельзя.

Если Excel находится в режиме конструктора, тестирование элементов управления невозможно. В этом случае нужно выйти из режима конструктора, щелкнув на кнопке Разработчик –> Элементы управления –> Режим конструктора. Эта кнопка работает, как переключатель.

Настройка элементов управления пользовательского диалогового окна

Продолжим описание использования элементов управления в UserForm. После того, как элементов управления помещен в диалоговое окно, его можно переместить и изменить размер. Можно выделить несколько элементов управления. Для этого следует удерживать нажатой клавишу <Shift> и щелкать на объектах либо обвести указателем мыши необходимые элементы управления.

В форме UserForm содержатся вертикальные и горизонтальные направляющие, которые помогают выровнять добавленные в диалоговое окно элементы управления. При добавлении или перемещении элемент управления привязывается к направляющим, что облегчает упорядочение таких элементов в окне. Если вы не используете направляющие, можете их отключить, выбрав в VBE команду Tools –> Options. В диалоговом окне Options перейдите на вкладку General и выберите соответствующие параметры в разделе Form Grid Settings.

Меню Format окна VBE предоставляет несколько команд, которые позволяют точно разместить и выровнять элементы управления в диалоговом окне. Перед использованием этих команд необходимо указать элементы управления, к которым они будут применяться (рис. 5).

Рис. 5. Выравнивание элементов в форме UserForm

Если выделено несколько элементов управления, на выделяющей рамке одного из них (обычно последнего) вместо обычных черных маркеров появляются белые. Это означает, что этот элемент управления играет роль основы, на базе которой определяются размеры и расположение других элементов управления.

Изменение свойств элементов управления

Каждый элемент управления характеризуется набором параметров, которые определяют внешний вид и поведение элемента управления. Свойства элемента управления можно изменять в следующих случаях:

  • В момент проектирования при разработке пользовательского диалогового окна. Для этого используется окно Properties.
  • В процессе выполнения, когда пользовательское диалоговое окно отображается на экране. Для этого воспользуйтесь инструкциями VBA.

Работа с окном Properties. В VBE окно Properties позволяет изменять свойства выделенного элемента управления (это может быть обычный элемент управления или сама форма UserForm, рис. 6).

Рис. 6. Окно Properties для выделенного элемента управления OptionButton

В окне Properties есть две вкладки. На вкладке Alphabetic свойства выбранного объекта отображаются в алфавитном порядке. На вкладке Categorized эти свойства сгруппированы по категориям. Обе вкладки отображают одни и те же свойства.

Для того чтобы изменить свойство, необходимо щелкнуть на нем и ввести новое значение. Некоторые свойства могут принимать только ограниченный набор допустимых значений, выбираемых из соответствующего списка. После щелчка на таком свойстве в окне Properties будет отображена кнопка со стрелкой, указывающей вниз. Щелкните на этой кнопке, чтобы выбрать значение из предложенного списка. Например, свойство TextAlign может принимать одно из следующих значений: 1 — fmTextAlignLeft, 2 — fmTextAlignCenter и 3 — fmTextAlignRight.

После выделения отдельных свойств (например, Font и Picture) рядом с ними отображается небольшая кнопка с троеточием. Щелчок на этой кнопке приводит к вызову диалогового окна настройки свойства.

Для свойства Picture элемента управления Image необходимо указать графический файл или вставить изображение из буфера обмена. В последнем случае следует сначала скопировать его в буфер обмена, а затем выбрать свойство Picture элемента управления Image и нажать комбинацию клавиш <Ctrl+V> для вставки содержимого буфера обмена. Если выделить два или более элементов управления одновременно, в окне Properties отобразятся только те свойства, которые являются общими для этих объектов.

Объекту UserForm присущ ряд свойств, значения которых можно изменять. Эти свойства применяются в качестве значений, заданных по умолчанию, для элементов управления, которые добавляются в пользовательские диалоговые окна. Например, если изменить свойство Font пользовательского диалогового окна, все добавленные в окно элементы управления будут применять этот шрифт.

Общие свойства. Каждый элемент управления имеет как собственный набор уникальных свойств, так и ряд общих свойств, присущих другим элементам управления. Например, все элементы управления имеют свойство Name и свойства, определяющие его размер и расположение на форме (Height, Width, Left и Right). Если вы собираетесь работать с элементом управления с помощью кода VBA, присвойте ему значащее имя. Например, первый элемент управления OptionButton, который добавлен в пользовательское диалоговое окно, по умолчанию получит имя ОрtionButton1. В коде ссылка на этот объект будет выглядеть следующим образом: OptionButton1.Value = True. Но если элементу управления OptionButton присвоить описательное имя (например, obLandscape), то можно использовать такой оператор: obLandscape.Value = True.

Многие пользователи предпочитают имена, которые указывают на тип объекта. В предыдущем примере был использован префикс ob, который указывает на то, что объект является элементом управления OptionButton.

Можно изменять значения свойств нескольких элементов управления одновременно. Например, вы вправе создать на форме несколько элементов управления OptionButton и выровнять их по левому краю. Для этого достаточно выделить все элементы управления OptionButton и изменить значение свойства Left в окне Properties. Все выделенные элементы управления примут новое значение свойства Left.

Чтобы получить доступ к справочной информации о свойствах различных элементов управления, щелкните на свойстве в окне Properties и нажмите клавишу <F1>.

Советы по использованию клавиатуры. Многие пользователи предпочитают перемещаться по диалоговым окнам с помощью клавиатуры. Комбинации клавиш <Таb> и <Shift+Tab> позволяют циклически переключаться между элементами управления. Чтобы удостовериться, что диалоговое окно корректно реагирует на команды с клавиатуры, обратите внимание на такие моменты: порядок просмотра элементов управления и комбинации клавиш.

Порядок просмотра определяет последовательность, в которой активизируются элементы управления после нажатия пользователем клавиши <Таb> или комбинации клавиш <Shift+Tab>. Кроме того, порядок активизации указывает, какой элемент управления по умолчанию выделяется на форме первым. Если пользователь вводит текст в элемент управления TextBox, то этот элемент считается активным. Если после этого щелкнуть на элементе управления OptionButton, то именно он станет активным. Элемент управления, назначенный первым для просмотра, будет активным в момент открытия диалогового окна.

Для того чтобы указать порядок активизации, выберите команду View –> Tab Order. Кроме того, можно щелкнуть правой кнопкой мыши на UserForm и выбрать пункт Тab Order из появившегося контекстного меню. Excel отобразит диалоговое окно Tab Order (Порядок просмотра, рис. 7).

Рис. 7. В диалоговом окне Tab Order измените порядок просмотра элементов управления

Также можно указать порядок активизации элемента управления с помощью окна Properties (см. рис. 6, самое последнее из отраженных свойств). Первый активизируемый элемент управления будет иметь свойство Tablndex = 0. Изменение значения свойства Tablndex текущero объекта приведет к изменению значений свойств Tablndex других элементов правления. Изменения вносятся автоматически. Вы можете удостовериться в том, что значения свойства Tablndex всех элементов управления не больше количества элементов управления в диалоговом окне. Если нужно удалить элемент управления из списка активизируемых объектов, то присвойте его свойству TabStop значение False.

Одни элементы управления, такие как Frame и MultiPage, служат контейнерами для других элементов управления. Элементы управления в таком контейнере имеют собственный порядок просмотра (активизации). Для установки порядка просмотра группы элементов управления OptionButtons, находящихся внутри элемента управления Frame, выделите элемент управления Frame до того, как будет выполнена команда View –> Tab Order.

Большинству элементов управления диалогового окна можно назначить комбинацию клавиш. Таким образом, пользователь получит доступ к элементу управления, нажав <Alt> и указанную клавишу. Применив свойство Accelerator в окне Properties, можно определить клавишу для активизации элемента управления.

Некоторые элементы управления, например, TextBox, лишены свойства Accelerator, поскольку не отображают значение свойства Caption. Но к таким элементам можно получить доступ с помощью клавиатуры, воспользовавшись свойством Label. Присвойте клавишу элементу управления Label и расположите его в порядке просмотра перед элементом TextBox.

Отображение пользовательского диалогового окна

Для того чтобы отобразить пользовательское диалоговое окно с помощью VBA, необходимо создать процедуру, которая вызывает метод Show объекта UserForm. Форму UserForm невозможно отобразить, не выполнив как минимум одну строку кода VBA:

Sub ShowForm()

     UserForm1.Show

End Sub

Данная процедура должна располагаться в стандартном модуле VBA, а не в модуле формы UserForm. При отображении пользовательская форма остается на экране до тех пор, пока ее не скроют. Обычно в нее добавляют элемент управления CommandButton, который запускает процедуру закрытия формы. Эта процедура либо выгружает пользовательскую форму с помощью метода Unload, либо удаляет ее с экрана с помощью метода Hide объекта UserForm.

Отображение немодальной формы. По умолчанию отображается модальная форма. Это означает, что форма должна исчезнуть с экрана прежде, чем пользователь выполнит какие-либо действия на рабочем листе (т.е. редактирование данных невозможно). Немодальную форму также можно отобразить. В этом случае вы вправе продолжать работу в Excel, не скрывая саму форму. Для отображения немодальной формы используется следующий синтаксис:

UserForm1.Show vbModeless

Тестирование пользовательского диалогового окна. Обычно в процессе разработки возникает необходимость в тестировании формы UserForm. Для этого можно воспользоваться одним из способов:

  • выполните команду Run –> Run Sub/UserForm;
  • нажмите <F5>;
  • щелкните на кнопке Run Sub/UserForm, которая находится на стандартной панели инструментов.

Выбор одного из этих методов приводит к запуску события инициализации диалогового окна. Как только диалоговое окно будет отображено в тестовом режиме, можно проверить порядок активизации объектов, а также поддержку комбинаций клавиш.

Отображение пользовательского диалогового окна на основе значения переменной. В некоторых случаях приходится выбирать, какое окно UserForm будет отображено. Если название пользовательского диалогового окна хранится в виде строковой переменной, можно воспользоваться методом Add для добавления объекта UserForm в коллекцию UserForms с последующим обращением к методу Show из коллекции UserForms. В приведенном ниже примере название объекта UserForm присваивается переменной MyForm, после чего отображается пользовательское диалоговое окно.

MyForm = «UserForm1»

UserForms.Add(MyForm).Show

Загрузка пользовательского диалогового окна. В VBA поддерживается оператор Load. Загрузка пользовательского диалогового окна приводит к сохранению объекта формы в памяти. Однако до тех пор пока не будет выполнен метод Show, форма останется невидимой для остальной части программы. Для загрузки окна UserForm1 воспользуйтесь оператором:

Load UserForm1

Если вы применяете сложное диалоговое окно, то вам может понадобиться предварительно загрузить его в память, чтобы в случае необходимости быстро отобразить его с помощью метода Show. Как правило, использовать метод Load в подобном случае не имеет смысла.

О процедурах обработки событий. Как только диалоговое окно появляется на экране, пользователь начинает с ним взаимодействовать, т.е. генерирует события. Например, щелчок на элементе управления CommandButton приводит к возникновению события Click объекта CommandButton. Вам необходимо создать процедуры (обработчики событий), которые будут выполняться при возникновении соответствующих событий.

Процедуры обработки событий находятся в модуле кода объекта UserForm. Наряду с этим процедура обработки события может вызывать другие процедуры, которые находятся в стандартном модуле VBA.

В коде VBA можно изменять свойства элементов управления, пока пользовательское диалоговое окно отображается на экране (т.е. на этапе выполнения). Например, можно назначить элементу управления ListBox процедуру, которая изменяет текст элемента управления Label при выборе элемента списка.

Закрытие пользовательского диалогового окна

Для закрытия формы UserForm1 воспользуйтесь командой: Unload UserForm1. Если же код находится в модуле кода формы UserForm, воспользуйтесь оператором: Unload Me. В этом случае ключевое слово Me применяется для идентификации пользовательской формы.

Обычно в коде VBA команда Unload выполняется только после того, как форма UserForm выполнит все свои функции. Например, форма UserForm может содержать элемент управления CommandButton, который используется в качестве кнопки ОК. Щелчок на этой кнопке приводит к выполнению заранее определенного макроса. Одна из функций макроса заключается в выгрузке формы UserForm из памяти. В результате пользовательское диалоговое окно отображается на экране до тех пор, пока макрос, содержащий оператор Unload, не завершает свою работу.

Когда форма UserForm выгружается из памяти, элементы управления, содержавшиеся на ней, возвращаются в первоначальное состояние. Другими словами, в коде нельзя обращаться к значениям, указываемым пользователем, после того как форма будет выгружена из памяти. Если значения, введенные пользователем, будут применяться позже (после выгрузки диалогового окна UserForm), то необходимо присвоить их переменной с областью действия Public, которая определена в стандартном модуле VBA. Кроме того, значение всегда можно сохранить в ячейке листа.

Окно формы UserForm автоматически выгружается из памяти после того, как пользователь щелкает на кнопке Закрыть (обозначается символом х в заголовке окна). Это действие также приводит к возникновению события QueryClose объекта UserForm, за которым следует событие Terminate пользовательского диалогового окна. Объект UserForm может использовать метод Hide. После его вызова диалоговое окно исчезает, но остается в памяти, поэтому в коде можно получить доступ к различным свойствам элементов управления:

UserForml.Hide

Если ваш код находится в модуле кода объекта UserForm, можно воспользоваться оператором:

Me.Hide

Если по какой-либо причине пользовательское диалоговое окно должно быть немедленно скрыто в процессе выполнения макроса, воспользуйтесь методом Hide в самом начале процедуры, а затем укажите команду DoEvents. Например, в следующей процедуре форма UserForm немедленно исчезнет после того, как пользователь щелкнет на кнопке CommandButton1. Последний оператор процедуры выгружает пользовательское диалоговое окно из памяти.

Private Sub CommandButton1_Click()

   Me.Hide

   Application.ScreenUpdating = True

   For r = 1 To 10000

      Cells(r, 1) = r

   Next r

   Unload Me

End Sub

В рассматриваемом примере переменной ScreenUpdating присвоено значение True, в результате чего Excel полностью скрывает окно UserForm. Если этот оператор не использовать, окно UserForm остается видимым.

Пример создания пользовательского диалогового окна

В примере представлено диалоговое окно, предназначенное для получения имени и пола пользователя. В диалоговом окне вы найдете элемент управления TextBox, используемый для ввода имени, и два элемента управления OptionButton для указания пола. Информация, полученная в диалоговом окне, заносится в пустую строку рабочего листа.

Создание пользовательской формы. Создайте рабочую книгу, содержащую только один рабочий лист. Нажмите комбинацию клавиш <Alt+F11> для активизации VBE. В окне Project выберите проект рабочей книги и выполните команду Inserts –> UserForm. Воспользуйтесь окном Properties для изменения значения свойства Caption формы UserForm на Укажите имя и пол (если окно Properties не отображается, нажмите <F4>).

Рис. 8. Создание пользовательской формы

Добавьте элемент управления Label и настройте его свойства (рис. 9):

Свойство          Значение

Accelerator        И

Caption               Имя:

Tablndex             0

Рис. 9. Пользовательская форма с элементами управления

Добавьте элемент управления TextBox и измените его свойства:

Name                   TextName

Tablndex             1

Добавьте элемент управления Frame и измените его свойства:

Caption                Пол

Tablndex             2

Добавьте элемент управления OptionButton в состав элемента Frame и измените его свойства:

Accelerator        М

Caption              Мужчина

Name                   OptionMale

Tablndex             0

Добавьте еще один элемент управления OptionButton в состав элемента Frame и измените его свойства:

Accelerator        Ж

Caption               Женщина

Name                   OptionFemale

Tablndex             1

Добавьте элемент управления CommandButton за пределами элемента Frame и измените его свойства:

Caption                OK

Default                 True

Name                   OKButton

Tablndex             3

Добавьте еще один элемент управления CommandButton и настройте его свойства:

Caption               Отмена

Default                False

Name                   CloseKButton

Tablndex             4

При создании нескольких похожих элементов управления может оказаться, что быстрее копировать существующий элемент управления, чем создавать новый. Для копирования элемента управления удерживайте нажатой клавишу <Ctrl> при перетаскивании элемента управления, что приведет к созданию копии. После этого останется изменить свойства скопированного элемента управления.

Создание кода для отображения диалогового окна. После создания элементов управления на лист необходимо добавить элемент управления ActiveX, называемый Кнопка (CommandButton). Эта кнопка будет запускать процедуру, которая предназначена для отображения формы UserForm. Для этого выполните следующие действия:

  1. Перейдите в окно Excel (например, воспользуйтесь комбинацией клавиш <Alt+F11>).
  2. Выберите команду Разработчика –> Элементы управления –> Вставить и щелкните на значке Кнопка (CommandButton), который находится в разделе Элементы ActiveX.
  3. Разместите кнопку на рабочем листе. Чтобы измените ее подпись, щелкните на кнопке правой кнопкой мыши и выберите в контекстном меню команду Объект CommandButton –> Edit. Для изменения других свойств объекта щелкните на нем правой кнопкой мыши и выберите команду Properties.
  4. Дважды щелкните на объекте CommandButton. Это приведет к активизации VBE. При этом отобразится модуль кода для листа с открытой пустой процедурой обработки событий объекта CommandButton, который расположен на рабочем листе.
  5. Введите единственный оператор в процедуру CommandButton1_Click (рис. 10). В процедуре используется метод Show объекта UserForml для отображения пользовательского диалогового окна.

Рис. 10. Процедура CommandButton1_Click вызывается после щелчка на кнопке рабочего листа

Тестирование диалогового окна. После щелчка на кнопке, находящейся на рабочем листе, ничего не произойдет. Точнее, кнопка будет выделена, но это не приведет к инициализации каких-либо действий. Причина этого заключается в том, что программа Excel по-прежнему остается в режиме конструктора, в который она переходит автоматически после добавления элемента управления ActiveX. Для выхода из режима конструктора щелкните на кнопке Разработчик –> Элементы управления –> Режим конструктора. Если же требуется изменить кнопку, снова перейдите в режим конструктора. После выхода из режима конструктора щелчок на кнопке приведет к отображению пользовательского диалогового окна.

Когда диалоговое окно будет отображено, введите произвольный текст в текстовом поле и щелкните на кнопке ОК. В результате ничего не произойдет, что совершенно естественно, так как для объекта UserForm не создано ни одной процедуры обработки событий. Для закрытия диалогового окна щелкните на крестике в его заголовке.

Добавление процедур обработки событий. Перейдите в VBE. Удостоверьтесь в том, что пользовательское окно отображено на экране, и дважды щелкните на кнопке Отмена. Активизируется окно кода для формы UserForm, а также добавляется пустая процедура CloseButton_Click. Обратите внимание, что название процедуры состоит из имени объекта, символа подчеркивания и названия обрабатываемого события. Добавьте в процедуру единственный оператор:

Private Sub CloseButton_Click()

   Unload UserForm1

End Sub

Эта процедура, которая вызывается после щелчка на кнопке Отмена, выгружает из памяти форму UserForm1.

Щелкните на значке View Object в верхней части окна Project Explorer или дважды кликните на строке UserForm1, чтобы отобразить форму UserForm1. Дважды щелкните на кнопке ОК и введите код процедуры – обработчика событий для события Click объекта OKButton:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

Private Sub OKButton_Click()

    Dim NextRow As Long

‘   Проверка активности листа Лист1

    Sheets(«Лист1»).Activate

   Проверка ввода имени

    If TextName.Text = «» Then

        MsgBox «Введите имя.»

        TextName.SetFocus

        Exit Sub

    End If

‘   Определение следующей пустой строки

    NextRow = _

      Application.WorksheetFunction.CountA(Range(«A:A»)) + 1

   Передача имени

    Cells(NextRow, 1) = TextName.Text

‘   Передача пола

    If OptionMale Then Cells(NextRow, 2) = «Мужчина»

    If OptionFemale Then Cells(NextRow, 2) = «Женщина»

   Очистка элементов управления для ввода следующей записи

    TextName.Text = «»

    TextName.SetFocus

    OptionMale = False

    OptionFemale = False

End Sub

Перейдите в Excel и щелкните на кнопке еще раз, чтобы отобразить пользовательское диалоговое окно. С его помощью можно добавлять новые имена в рабочий лист.

Процедура OKButton_Click работает следующим образом. Сначала она проверяет, активен ли лист Лист1, введено ли имя. После этого запускается функция Excel СЧЁТЗ (CountA) для определения следующей пустой ячейки в столбце А. Затем текст из текстового поля TextBox передается в определенную ячейку столбца А. С помощью операторов If определяется выделенный элемент управления OptionButton, что обеспечивает запись соответствующего текста в столбец В (пол). Далее элементы диалогового окна очищаются и окно перезапускается, чтобы обеспечить возможность введения следующей записи. Заметим, что щелчок на кнопке ОК не приведет к закрытию диалогового окна. Для завершения ввода данных (и выгрузки пользовательского диалогового окна) щелкните на кнопке Отмена.

Проверьте работоспособность комбинаций клавиш: Alt+М – активизирует мужской пол, Alt+Ж – женский. Рабочая книга с рассмотренным примером находится в файле get name and sex.xlsm.

События объекта User Form

Каждый элемент управления в форме UserForm (а также сам объект UserForm) разрабатывается для того, чтобы реагировать на определенные события. Эти события возникают в результате действий пользователя или генерируются программой Excel. Можно создать код, который будет выполняться при возникновении определенного события. Некоторые действия приводят к возникновению сразу нескольких событий. Например, щелчок на кнопке со стрелкой, направленной вверх, в элементе управления SpinButton приведет к возникновению события SpinUp и события Change. После того как пользовательское диалоговое окно будет отображено с помощью метода Show, Excel сгенерирует события Initialize и Activate объекта UserForm. В Excel также поддерживаются события, связанные с объектами Sheet (Лист), Chart (Диаграмма) и ThisWorkbook (ЭтаКнига).

Получение дополнительных сведений о событиях. Для того чтобы получить информацию о событиях, которые генерируются конкретным элементом управления, выполните следующее:

  • Добавьте элемент управления в пользовательское диалоговое окно.
  • Дважды щелкните на элементе управления, чтобы открыть модуль кода для объекта UserForm. VBE вставит пустую процедуру обработки события, принятого по умолчанию.
  • Щелкните на раскрывающемся списке в правом верхнем углу окна модуля и просмотрите полный список событий, которые поддерживаются текущим элементом управления (на рис. 11 показан список событий для элемента управления CheckBox).
  • Выберите событие из списка, и VBE создаст пустой обработчик события.

Рис. 11. Список событий для элемента управления CheckBox

Имя процедуры обработки событий включает имя объекта, который сгенерировал событие. Таким образом, если изменить имя элемента управления, придется внести соответствующие изменения и в имя процедуры обработки события. Имя процедуры не изменяется автоматически! Чтобы облегчить работу, присвойте описательные имена элементам управления до того, как приступите к созданию процедуры обработки соответствующих событий.

События объекта UserForm. Несколько событий непосредственно связано с отображением и выгрузкой объекта UserForm:

  • Происходит перед загрузкой и отображением формы UserForm. Не происходит, если объект UserForm до этого был скрыт.
  • Происходит в момент активизации объекта UserForm.
  • Происходит в момент деактивизации объекта UserForm. Не происходит при сокрытии формы UserForm.
  • Происходит перед выгрузкой объекта UserForm.
  • Происходит после выгрузки объекта UserForm.

Важно правильно выбрать подходящее событие для процедуры обработки событий, а также проанализировать порядок выполнения событий. Использование метода Show приводит к возникновению событий Initialize и Activate (в указанном порядке). Применение команды Load приводит к вызову события Initialize. Команда Unload вызывает события QueryClose и Terminate (в указанном порядке). Метод Hide не приводит к вызову каких-либо событий.

В файле userform events.xlsm описанные события перехватываются и в момент возникновения события возникает окно сообщения. Если изучение событий объекта UserForm вызывает у вас затруднения, то, проанализировав код этого примера, вы получите ответы на многие вопросы.

События элемента управления SpinButton. Для того чтобы разобраться в концепции событий, мы подробно рассмотрим события, связанные с элементом управления SpinButton (рис. 12). Файл spinbutton events.xlsm демонстрирует применение событий, генерируемых объектами SpinButton и UserForm (первый содержится во втором). Рабочая книга включает несколько процедур обработки событий — по одной для каждого события элемента управления SpinButton и объекта UserForm. Каждая из этих процедур добавляет текст в столбце А с описанием события.

Рис. 12. События элемента управления SpinButton

Пользователь может управлять объектом SpinButton с помощью мыши или (если элемент управления активен) клавиш управления курсором. Когда пользователь щелкает мышью на верхней кнопке элемента управления SpinButton, происходят следующие события: Enter (генерируется только в том случае, если элемент управления неактивен); Change; SpinUp.

Пользователь может нажать клавишу <Таb> для того, чтобы сделать активным элемент управления SpinButton. Только после этого можно использовать клавиши управления курсором для изменения значения элемента управления. Если все именно так и происходит, то события генерируются в следующем порядке: Enter; KeyDown; Change; SpinUp (или SpinDown); KeyUp.

Элемент управления SpinButton может изменяться в коде VBA, что также провоцирует возникновение соответствующих событий. Например, оператор SpinButton1.Value = 0 устанавливает свойство Value элемента управления SpinButton1 равным 0, а это приводит к возникновению события Change. Такой результат достигается только в том случае, если исходное свойство Value не равно нулю.

Вы вправе предположить, что выполнить отмену генерирования событий можно, установив свойство EnableEvents объекта Application равным False. Но это свойство поддерживается только объектами, которые являются «истинными» в Excel: Workbook, Worksheet и Chart.

Совместное использование элементов управления SpinButton и TextBox. Элемент управления SpinButton имеет свойство Value, но не может отображать значение этого свойства. В большинстве случаев требуется, чтобы пользователь мог изменить значение элемента управления SpinButton непосредственно, а не многократно щелкая на элементе управления. Эффективным решением может стать объединение элемента управления SpinButton с элементом управления TextBox, что позволяет пользователю вводить значение элемента управления SpinButton непосредственно, используя для этого поле элемента управления TextBox. Кроме того, щелчок на элементе управления SpinButton позволит изменить значение, отображаемое в элементе управления TextBox.

На рис. 13 приведен пример (см. также файл spinbutton and textbox.xlsm). Свойство Min элемента управления SpinButton имеет значение 1, а свойство Мах— значение 100. Таким образом, щелчок на одной из стрелок элемента управления SpinButton приведет к изменению значения в пределах от 1 до 100. Код, реализующий «связывание» элементов управления SpinButton и TextBox сводится к созданию процедур обработки событий, которые будут синхронизировать свойство Value элемента управления SpinButton и свойство Text элемента управления TextBox.

Рис. 13. Комбинирование элементов управления SpinButton и TextBox

Представленная процедура выполняется каждый раз при возникновении события Change элемента управления SpinButton. Таким образом, процедура выполняется тогда, когда пользователь щелкает на элементе управления SpinButton или изменяет его значение, нажав одну из клавиш управления курсором.

Private Sub SpinButton1_Change()

    TextBox1.Text = SpinButton1.Value

End Sub

Если пользователь введет значение непосредственно в элемент управления TextBox, то будет сгенерировано событие Change, после чего должен выполняться следующий код:

Private Sub TextBox1_Change()

    Dim NewVal As Integer

    NewVal = Val(TextBox1.Text)

    If NewVal >= SpinButton1.Min And _

        NewVal <= SpinButton1.Max Then _

        SpinButton1.Value = NewVal

End Sub

Эта процедура начинается с вызова функции VBA Val, которая преобразует текст элемента управления TextBox в числовое значение (если элемент управления TextBox содержит строку, то функция Val возвращает значение 0). Следующий оператор определяет, попадает ли значение в указанный диапазон допустимых значений. Если это так, то свойство Value элемента управления SpinButton устанавливается равным значению, которое введено в поле элемента управления TextBox.

Пример организован таким образом, что щелчок на кнопке ОК (которая называется OKButton) передает значение элемента управления SpinButton в активную ячейку. Процедура обработки события Click элемента управления CommandButton выглядит следующим образом:

Private Sub OKButton_Click()

   Enter the value into the active cell

    If CStr(SpinButton1.Value) = TextBox1.Text Then

        ActiveCell = SpinButton1.Value

        Unload Me

    Else

        MsgBox «Некорректная запись.», vbCritical

        TextBox1.SetFocus

        TextBox1.SelStart = 0

        TextBox1.SelLength = Len(TextBox1.Text)

    End If

End Sub

Данная процедура выполняет проверку: анализируются текст, введенный в поле элемента управления TextBox, и значения элемента управления SpinButton. Такая процедура обрабатывает ситуации неверного ввода данных. Например, если пользователь введет в поле элемента управления TextBox текст Зt, то значение элемента управления SpinButton не изменится, а результат, который помещается в активную ячейку, будет отличным от ожидаемого. Обратите внимание, что значение свойства Value элемента управления SpinButton преобразуется в строку с помощью функции CStr. Это позволяет предотвратить ошибку, которая возникает, когда числовое значение сравнивается с текстовым. Если значение элемента управления SpinButton не соответствует содержимому элемента управления TextBox, то на экране отображается специальное сообщение. Причем объект TextBox активен, а его содержимое — выделено (с помощью свойств SelStart и SelLength). Таким образом, пользователю проще исправить неправильные значения.

О свойстве Tag. Каждый объект UserForm и каждый элемент управления имеет свойство Tag. Оно не представляет конечные данные и по умолчанию не имеет значения. Свойство Tag можно использовать для хранения информации, которая будет применена в программе. Например, можно создать набор элементов управления TextBox в пользовательском диалоговом окне. От пользователя требуется ввести текст только в некоторые из них. В отдельные поля вводить текст необязательно. Можно применять свойство Tag для идентификации полей, которые нужно заполнять. В таком случае значение свойства Tag — это строка, например, Required. Поэтому при написании кода обработки введенных пользователем данных можно ссылаться на свойство Tag.

Приведенный ниже пример представляет собой функцию, которая проверяет все элементы управления TextBox объекта UserForm1 и возвращает количество пустых текстовых полей, которые требуют ввода информации.

Function EmptyCount()

   Dim ctl As Control

   EmptyCount= 0

   For Each ctl In UserFormi.Controls

      If TypeName(ctl) = «TextBox» Then

         If ctl.Tag = «Required» Then

            If ctl.Text = «» Then

               EmptyCount = EmptyCount + 1

            End If

         End If

      End If

   Next ctl

End Function

Ссылка на элементы управления пользовательского диалогового окна

При работе с элементами управления, находящимися в форме UserForm, код VBA обычно содержится в модуле кода объекта UserForm. Кроме того, на элементы управления диалогового окна можно ссылаться из модуля кода VBA общего назначения. Для выполнения этой задачи необходимо задать правильную ссылку на элемент управления, указав имя объекта UserForm. В качестве примера рассмотрим процедуру, которая введена в модуле кода VBA. Эта процедура отображает пользовательское диалоговое окно, которое называется UserForm1.

Sub GetData ()

   UserForm1.Show

End Sub

Предположим, что в диалоговом окне UserForm1 содержится текстовое поле TextBox1 и вам необходимо указать значение текстового поля по умолчанию:

Sub GetData()

   UserForm1.TextBox1.Value = «Джон Доу»

   UserForm1.Show

End Sub

Еще одним способом установки значения по умолчанию является использование события Initialize объекта UserForm. Можно написать код процедуры UserForm_Initialize, который будет располагаться в модуле кода диалогового окна:

Private Sub UserForm_Initialize()

   TextBox1.Value = «Джон Доу»

End Sub

Обратите внимание, что при обращении к элементу управления из модуля кода диалогового окна необязательно вводить в ссылку имя объекта UserForm. Подобное определение ссылок на элементы управления имеет свое преимущество: всегда можно воспользоваться средством Auto List Member, которое позволяет выбирать имена элементов управления из раскрывающегося списка.

Вместо того чтобы использовать фактическое имя объекта UserForm, предпочтительнее применить имя Me. В противном случае, если имя объекта UserForm изменится, вам придется изменять все ссылки (с его участием) в коде.

Использование коллекций элементов управления. Элементы управления пользовательских диалоговых окон образуют отдельную коллекцию. Например, следующий оператор отображает количество элементов управления в форме UserForm1:

MsgBox UserForm1.Controls.Count

В VBA не поддерживаются коллекции для каждого типа элемента управления. Например, не существует коллекции элементов управления CommandButton. Но тип элемента управления можно определить с помощью функции TypeName. Следующая процедура использует структуру For Each для циклического просмотра элементов коллекции Controls. В результате отображается количество элементов управления CommandButton, которые входят в коллекцию элементов управления объекта UserForm1 (этот код вы найдете в файле all userform controls.xlsm).

Sub CountButtons()

    Dim cbCount As Integer

    Dim ctl As Control

    cbCount = 0

    For Each ctl In UserForm1.Controls

        If TypeName(ctl) = «CommandButton» Then _

            cbCount = cbCount + 1

    Next ctl

    MsgBox cbCount

End Sub

Настройка панели инструментов Toolbox

Если объект UserForm активен в редакторе VBE, на панели Toolbox отображаются элементы управления, которые можно добавить в пользовательское диалоговое окно. Панель Toolbox изначально содержит одну вкладку. Щелкните на ней правой кнопкой мыши и в контекстном меню выберите параметр New Page (Добавить страницу). Кроме того, можно изменить текст, который отображается на вкладке. Для этого выберите параметр Rename (Переименовать) из контекстного меню.

Рекомендуется предварительно настроить элементы управления и сохранить их для дальнейшего использования. Можно, например, в форме создать элемент управления CommandButton, который настроен на выполнение роли кнопки ОК. Можно изменять параметры кнопки: Width (Ширина), Height (Высота), Caption (Подпись), Default (По умолчанию) и Name (Имя). После этого перетащите модифицированный элемент управления CommandButton на панель инструментов Toolbox. Это приведет к созданию элемента управления. Щелкните на элементе управления правой кнопкой мыши, чтобы переименовать его или изменить значок.

Также можно создать раздел панели Toolbox, в котором будет содержаться несколько элементов управления. Например, вы вправе создать два элемента управления CommandButton, которые будут представлять кнопки ОК и Отмена. Настройте их так, как это необходимо. Затем выберите обе кнопки и переместите их на панель инструментов Toolbox. Впоследствии можно использовать новый элемент управления панели Toolbox для быстрого создания необходимых кнопок.

Этот метод также применим к элементам управления, которые используются в качестве контейнера. Например, создайте элемент управления Frame и добавьте в него четыре модифицированных элемента управления OptionButton (соответствующим образом расположив их на форме). После этого перетащите элемент управления Frame на панель инструментов Toolbox, чтобы создать модифицированный элемент управления Frame.

Можно разместить модифицированные элементы управления на отдельной вкладке панели Toolbox. Таким образом, появляется возможность экспортировать вкладку панели Toolbox для совместного применения другими пользователями Excel. Для экспорта вкладки панели Toolbox щелкните на ней правой кнопкой мыши и выберите пункт меню Export Page.

Среди прилагаемых к заметке файлов находится страничный файл под именем newcontrols.pag, который включает некоторые настроенные элементы управления. Можно импортировать этот файл в качестве новой вкладки окна Toolbox. Щелкните правой кнопкой мыши на вкладке и выберите команду Import Page. В результате панель Toolbox будет как на рис. 14.

Рис. 14. В окне Toolbox появилась страница с новыми элементами управления

Добавление элементов управления ActiveX

В пользовательском диалоговом окне содержатся и другие элементы управления ActiveX, разработанные компанией Microsoft и независимыми производителями. Для того чтобы добавить дополнительные элементы управления ActiveX на панель инструментов Toolbox, щелкните правой кнопкой мыши на ней и выберите пункт Additional Controls (Дополнительные элементы управления). В результате будет отображено диалоговое окно, показанное на рис. 15.

Рис. 15. В диалоговом окне Additional Controls можно найти дополнительные элементы управления ActiveX

В диалоговом окне Additional Controls содержатся все элементы управления ActiveX, установленные в системе. Выберите элементы управления, которые необходимо добавить на панель инструментов. После этого щелкните на кнопке ОК для добавления значков каждого из выбранных элементов управления. Не все элементы управления ActiveX, установленные в системе, поддерживаются пользовательскими диалоговыми окнами. Более того, большая их часть не поддерживается, к тому же некоторые элементы управления требуют лицензии на использование в приложениях. Если лицензия отсутствует, на экране появится сообщение об ошибке.

Создание шаблонов диалоговых окон

Зачастую при создании пользовательского диалогового окна каждый раз на форму добавляются одни и те же элементы управления. Например, все пользовательские диалоговые окна имеют два элемента управления CommandButton, используемых в качестве кнопок ОК и Отмена. В предыдущем разделе рассматривались методы комбинирования элементов управления с целью получения одного элемента управления, обладающего функциями двух. Еще одной программной уловкой может служить шаблон диалогового окна, который при необходимости импортируется для последующего создания на его основе других проектов. Преимущество шаблонного подхода заключается в следующем: процедуры обработки событий сохраняются вместе с шаблоном.

Начните с создания пользовательского диалогового окна, содержащего все элементы управления и настройки, которые необходимо повторно использовать в других проектах. После этого убедитесь, что диалоговое окно выделено. Выберите команду File –> Export File (или нажмите комбинацию клавиш <Ctrl+E>). После этого на экране появится запрос на ввод имени файла. Затем для создания проекта на основе шаблона выполните команду File –> lmport File, чтобы загрузить ранее сохраненное диалоговое окно.

Имитация диалоговых окон Excel. Внешний вид и поведение диалоговых окон Windows изменяются от программы к программе. При разработке приложений для Excel рекомендуется придерживаться стиля диалоговых окон Excel. Наилучшим методом изучения эффективных способов создания диалоговых окон является повторное создание одного из стандартных диалоговых окон Excel. Например, удостоверьтесь, что вы правильно определили комбинации клавиш и активизировали элементы управления. Для создания копии одного диалогового окна Excel следует протестировать его в различных условиях. Один только анализ диалоговых окон Excel поможет улучшить познания в вопросах структуры окон и методов создания элементов управления. Со временем вы убедитесь, что невозможно повторить отдельные диалоговые окна Excel даже с помощью VBA.

[1] По материалам книги Джон Уокенбах. Excel 2010. Профессиональное программирование на VBA. – М: Диалектика, 2013. – С. 405–438.

In this Article

  • Creating a UserForm
  • Creating a Text Box
  • Creating a Label Control
  • Creating a Combo Box Control
    • Adding values to the Combo Box
  • Creating a List Box Control
    • Adding values to the List Box
  • Creating a Check Box Control
  • Creating an Option Group Control with Option Buttons
  • Creating a Command Button to Exit the Form
    • Adding Code to the Command Button

This article will demonstrate how to use Controls in UserForms in Excel VBA.

VBA has the ability to create forms that the user can interact with such as Invoice forms, or Contact details.  A form can contain a variety of Form Controls such as text boxes, Combo Boxes, List Boxes and Command Buttons.  This article will cover the most popular controls used on User forms namely Text Boxes, Labels, Combo Boxes, List Boxes, Check Boxes and Option Groups.

To find out more about built in user forms and creating custom user forms in Excel, click here.

Creating a UserForm

To create a UserForm in Excel VBA, we first need to open the VBE Editor.

To insert a new user form into your code, select the UserForm option from the Insert Menu.

vba vbe insert userform

A new user form will appear in the Project Explorer and will be shown in the Code Window on the right.

vba vbe userform

You can rename your form using the Properties box.  This should appear below your Project Explorer.

If it is how visible, Press F4 or click View, Properties Window.

VBATextBox Name Form

Click in the Name property and rename your form.

We can now start populating our form with controls – the text box control is the most popular control along with the label control and command button.

To populate the form with controls, we need to switch on the Toolbox.

In the Menu, select View > Toolbox.

VBATextBox View Menu

Creating a Text Box

To create a Text Box on your form, select the Text Box control in the Toolbox.

VBATextBox Toolbox

Drag a box shape on the form with your mouse, holding the left button down, and then release the mouse button.

VBATextBox DrawTextbox

VBATextBox TextBoxName

As this is the first Text Box we are creating, it will be named TextBox1. As with the form, you can use the Properties window to rename the text box.

VBATextBox Rename TextBox

We can continue to create as many text boxes in our form that we require and name them as appropriate using the Name property in the Properties Window.

VBAControls TextBox

Creating a Label Control

A label control tells us what the text box is going to be used to hold. You drag on the form in the same way as you do for a Text Box, and then you can type the required text within the label control eg: First Name as shown below.

VBATextBox DrawLabel

As with the text boxes, continue to create as many as are required in the form.

VBAControls Labels

Creating a Combo Box Control

A Combo Box (or a drop-down box) allows the user to select from a list of values.   To create a combo box, click in the toolbox on the Combo Box control, and click and drag the combo box in your form.

VBAControls ComboBox

Name the Combo Box appropriately.

VBAControls ComboBox NameProperty

Adding values to the Combo Box

In order to populate it with values, we need to code into the Initialize method of the User form object.

To get to the Code Behind the Form (CBF), either double click on the form, or click on the code button in the Project Explorer to switch to code view.

VBAControls Code View

In the left hand drop down list, select User form, and then in the right-hand drop down list, select Initialize.

VBAControls Event

Type the following code within the Sub and End Sub to populate the drop down box:

Me.cboState.AddItem "Alabama"
Me.cboState.AddItem "Alaska"
Me.cboState.AddItem "Arizona"
Me.cboState.AddItem "Arkansas"

We can of course carry on an populate the list with the rest of the states in the USA!

To run the user form to see the list in action, 1) switch back to form view and then, 2) in the Toolbar, click on the Run button.

VBAControls RunForm

Click on the drop down arrow to see the list.

VBAControls DropDownList

We can also use a Range in Excel to populate the Combo Box.

Private Sub UserForm_Initialize()
 Dim rng As Range
 For Each rng In Range("A1:A50")
   Me.cboState.AddItem rng.Value
 Next rng
End Sub

This will pick up any values stored in the Range A1 to A50 and populate the drop down list accordingly.

VBAControls ComboBox Range

Creating a List Box Control

A List Box control work in the same way as a Combo Box control, but allows us to see all the options on the form in a list format.

Select the List Box control in the toolbox and then drag to create a list box on your form.

VBAControls ListBox

VBA Coding Made Easy

Stop 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!

automacro

Learn More

Adding values to the List Box

In the Initialize event of the form, type the following code:

Private Sub UserForm_Initialize()
  Dim rng As Range
  For Each rng In Range("A1:A50")
    Me.lstState.AddItem rng.Value
  Next rng
End Sub

When we run the form, the list box will be shown as demonstrated in the image below:

VBAControls ListBox Run

Creating a Check Box Control

Check Boxes enable the user to check or uncheck an option.

Select the Check Box control, and then click in the form where you wish it to go.

VBAControls CheckBox

Amend the caption and name of the Check Box in the Properties Window.

VBAControls CheckBox name

Creating an Option Group Control with Option Buttons

An Option Group allows the user to select from a number of available options. The first step in creating an option group is to add a Frame Control to the form, and then to add the Option Buttons within the frame that has been added. By doing this, we ensure that when we run the form, only one of the Option Buttons within the frame can be selected at a time.

Select the Frame control in the toolbox and then drag to create a frame on your form.

VBAControls Frame

Select the Option Button control in the toolbox and then click WITHIN the frame created above to add option button into the frame. Repeat as required.

VBAControls OptionButtons

Click on the frame and 1) amend the name of the frame and the Caption. Then 2) click on each of the option buttons and amend the Caption.

VBA Programming | Code Generator does work for you!

VBAControls Option GroupCreating a Command Button to Exit the Form

At this stage, the only way of closing the form is to use the close button in the right-hand corner of the form control bar. A more efficient way to exit a form, and one in which we have more control over, is by creating an Exit button on the form.  This is done by means of the Command Button Control in the Toolbox.

Select the Command Button control, and then click and drag in your form to create the button.

VBAControls CommandButton

Using the Caption Property, change the caption of the command button to OK, and the Accelerator to “O”

VBAControls Button Properties

The purpose of the Accelerator is for the user to use the keyboard to activate the button, in this case Alt+O would activate the button.

VBAControls Button Accelerator

Adding Code to the Command Button

For the command button to work, we need to add code behind it so that when the button is clicked, the code runs. This is called the Click event of the button.

To get to the click event, double-click on the button in the design view of the form.

1) The Click event will be automatically created as this is the event that is most commonly used for Command buttons.

2) If we were to click in the Procedure drop-down box on the right hand side, we would see a list of all the Event Methods that are available to the Command Button.  This list changes according to what type of control we have created as there are different events available for different types of controls.

VBAControls Button Click Event

Type the following code into the click event of the command button.

Private Sub cmdOK_Click()
 Range("E1") = Me.txtFirstname
 Range("E2") = Me.txtSurname
 Range("E3") = Me.txtCellPhone
 Range("E4") = Me.cboState
 If Me.ckContactInfo = True Then
   Range("E5") = "SMS allowed"
 Else
   Range("E5") = "SMS not allowed"
 End If
 If Me.opt1.Value = True Then Range("E6") = Me.opt1.Caption
 If Me.opt2.Value = True Then Range("E6") = Me.opt2.Caption
 If Me.opt3.Value = True Then Range("E6") = Me.opt3.Caption
 Unload Me
End Sub

We can then run the form, fill in the text boxes and select from the drop down list.  We then click OK to enter the information into Excel.

VBAControls Form OK Click

Понравилась статья? Поделить с друзьями:
  • For pictures one word 7 letters
  • Form compound nouns using the word book
  • For picture one word game
  • Form building use the proper form of the word from the right column
  • For pics one word level 4