Excel vba control type

Содержание

  • 1 change control back ground color
  • 2 Change fonts of controls on a form
  • 3 Controls and Errors
  • 4 Control Types
  • 5 Determining the Type of a Control
  • 6 Intrinsic Constant Type of Control
  • 7 Manipulating a Single Control
  • 8 The For Each…Next statement executes a group of statements on each member of an array or collection
  • 9 The With…End With statement executes a series of statements on a single object or user-defined type
  • 10 With…End With construct is often used along with the For Each…Next construct

change control back ground color

   <source lang="vb">

Sub Form_Current()

   Dim ctl as Control
   For Each ctl In Controls
       If TypeOf ctl Is TextBox Then
           If IsNull(ctl.Value) Then
               ctl.BackColor = vbCyan
           Else
               ctl.BackColor = vbWhite
           End If
       End If
   Next ctl

End Sub

</source>
   
  

Change fonts of controls on a form

   <source lang="vb">

   Sub FormFonts (strFont As String)
      Dim frmCurrent As Form
      Dim ctlControl As Control
   
      For Each frmCurrent In Forms
         For each ctlControl In frmCurrent.Controls
            ctlControl.FontName = strFont
         Next
       Next
    
    End Sub
</source>
   
  

Controls and Errors

   <source lang="vb">

   Sub FormFonts(strFont As String)
      On Error GoTo FormFonts_Err
      Dim frmCurrent As Form
      Dim ctlControl As Control
   
      For Each frmCurrent In Forms
         For Each ctlControl In frmCurrent.Controls
            ctlControl.FontName = strFont
          Next
       Next
    

FormFonts_Exit:

       Exit Sub
    

FormFonts_Err:

       If Err.Number = 438 Then
          Resume Next
       Else
          MsgBox Err.Description
          Resume FormFonts_Exit
       End If

End Sub

</source>
   
  

Control Types

   <source lang="vb">

Sub main()

  For Each frmCurrent In Forms
     For Each ctlControl In frmCurrent.Controls
        If ctlControl.Type <> acCheckBox Then
           ctlControl.font = strFont
        End If
     Next
  Next

End Sub

</source>
   
  

Determining the Type of a Control

   <source lang="vb">

Sub FlipEnabled(frmAny As Form, ctlAny As Control)

   Dim ctl As Control
   ctlAny.Enabled = True
   ctlAny.SetFocus
   For Each ctl In frmAny.Controls
       If ctl.ControlType = acCommandButton Then
           If ctl.Name <> ctlAny.Name Then
               ctl.Enabled = Not ctl.Enabled
           End If
       End If
   Next ctl

End Sub

</source>
   
  

Intrinsic Constant Type of Control

   <source lang="vb">

acLabel Label
acRectangle Rectangle
acLine Line
acImage Image
acCommandButton Command button
acOptionButton Option button
acCheckBox Check box
acOptionGroup Option group
acBoundObjectFrame Bound object frame
acTextBox Text box
acListBox List box
acComboBox Combo box
acSubform Subform/subreport
acObjectFrame Unbound object frame or chart
acPageBreak Page break
acPage Page
acCustomControl ActiveX (custom) control
acToggleButton Toggle button
acTabCtl Tab

</source>
   
  

Manipulating a Single Control

   <source lang="vb">

Sub FormCaptions()

   Dim frm As Form
   For Each frm In Forms
       frm.Caption = frm.Caption & " - " & CurrentUser
   Next frm

End Sub

</source>
   
  

The For Each…Next statement executes a group of statements on each member of an array or collection

   <source lang="vb">

Private Sub cmdForEachNext_Click()

   Dim ctl As Control
   For Each ctl In Controls
       ctl.FontSize = 8
   Next ctl

End Sub

</source>
   
  

The With…End With statement executes a series of statements on a single object or user-defined type

   <source lang="vb">

Private Sub cmdWithEndWith_Click()

  With Me.txtAge " Your Text Field"s name
     .BackColor = 16777088
     .ForeColor = 16711680
     .Value = "Hello World"
     .FontName = "Arial"
  End With

End Sub

</source>
   
  

With…End With construct is often used along with the For Each…Next construct

   <source lang="vb">

Private Sub cmdForEachWith_Click()

   Dim ctl As Control
   For Each ctl In Controls
       With ctl
           .ForeColor = 16711680
           .FontName = "Arial"
           .FontSize = 14
       End With
   Next ctl

End Sub

</source>

“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.)

Программное создание элементов управления и добавление их на пользовательскую форму в VBA Excel. Метод Controls.Add — синтаксис, компоненты, примеры.

Программное (динамическое) создание элементов управления пользовательской формы в VBA Excel осуществляется с помощью метода Controls.Add.

Синтаксис метода Controls.Add

Set Var = Form.Controls.Add(ProgID, [Name], [Visible])

Описание компонентов метода

  • Var — объектная переменная, которой будет присвоен созданный элемент управления. Она может быть объявлена как Control, Object или Variant.
  • Form — имя пользовательской формы, на которую добавляется элемент управления.
  • ProgID — программный идентификатор создаваемого элемента управления.
  • Name — необязательный параметр, задающий имя добавляемого элемента управления.
  • Visible — необязательный параметр, определяющий видимость создаваемого элемента управления. Может принимать значение True или False.

ProgID и Name, используемые в выражениях метода Controls.Add заключаются в прямые кавычки. Смотрите в примерах.

Идентификаторы элементов управления формы

Элемент управления Программный идентификатор
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
OptionButton Forms.OptionButton.1
ScrollBar Forms.ScrollBar.1
SpinButton Forms.SpinButton.1
TextBox Forms.TextBox.1
ToggleButton Forms.ToggleButton.1

Программное создание элементов управления

Для реализации примеров необходимо открыть рабочую книгу Excel с поддержкой макросов (.xls или .xlsm) и в редакторе VBA создать пользовательскую форму UserForm1.

Пример 1
Программное создание элемента управления TextBox с присвоением его свойству «Text» значения «Привет!». Так как это свойство TextBox является свойством по умолчанию, вместо «myCont.Text» используем в коде для присвоения значения только имя переменной «myCont».

Sub Primer_1()

Dim myCont As Control

Set myCont = UserForm1.Controls.Add(«Forms.TextBox.1», «myTextBox1»)

myCont = «Привет!»

UserForm1.Show

End Sub

Так как мы присвоили вновь созданному элементу управления TextBox имя «myTextBox1», теперь обращаться к нему можно и по этому имени, например:
UserForm1.Controls("myTextBox1") = "Привет!"
Этой строкой можно заменить строку:
myCont = "Привет!"

Как видим, обращаться к добавленному элементу управления удобнее через переменную, чем по присвоенному имени.

Пример 2
Создание с помощью кода VBA Excel группы элементов управления ComboBox, присвоение соответствующим параметрам значений размеров и отступов.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

Sub Primer_2()

Dim myCont(1 To 5) As Control, i As Byte

  With UserForm1

    For i = 1 To 5

      Set myCont(i) = .Controls.Add(«Forms.ComboBox.1»)

        With myCont(i)

‘Заполняем все ComboBox одинаковыми списками

          .List = Array(«Привет1», «Привет2», _

          «Привет3», «Привет4», «Привет5»)

‘Добавляем размеры и отступы

          .Width = 200

          .Height = 20

          .Left = 20

          .Top = i * 10 + (i 1) * 20

        End With

    Next

    .Caption = «Пять полей со списком»

    .Height = 190

    .Width = 250

    .Show

  End With

End Sub


Как привязать стандартные события к динамически созданным элементам управления читайте в статье Привязка события к элементу управления.


UserForm and Controls — Properties

———————————————————————-

Contents:

UserForm and Controls

Basic Properties common to the UserForm and most Controls

Other Properties common to the UserForm and most Controls

Specifying Color in Properties Window

Applicability of Properties to UserForm and its Controls — A SnapShot

———————————————————————-

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. ActiveX controls can be used with VBA code or without, either directly on worksheets, while some can be used only on VBA UserForms. Using ActiveX Controls on a Worksheet have been illustrated in detail, in the separate section of «Excel VBA: ActiveX Controls, Form Controls & AutoShapes on a Worksheet».

Properties can be viewed in an alphabetical order or category wise by clicking the «Alphabetic» or «Categorized» options in the Properties Window, after selecting the respective Userform or Control. To set/edit, click on that property and make the change in its right column. For help on a Userform or Control property, in the Properties Window select the right column of that property and press F1.

Design-Time, Run-time and Break-time:

The time when an application is being developed in VBE (Visual Basic Environment) is termed as design-time. This is the time when you create a UserForm, add controls and set their properties. Run-time is the time when your code is being executed or the application is running. During this time the developer interacts with the application just like a user and the code cannot be edited then. Break-time is the time when an Application encounters any processing error that prevents the code from continuing or being executed further. Design-time manipulations are not permanent, while run-time are not. For ex, if you add a CheckBox in your code using the Add Method [Set ctrl = Controls.Add(«Forms.CheckBox.1»)], it will appear when the UserForm shows but when you return to VBE, the CheckBox will not be present. Similarly, if you set the Caption of an OptionButton in your code, the new set Caption will appear when the UserForm is displayed but will revert to its original in VBE. The ControlTipText property is set during design-time but is visible on the control during run-time only.

UserForm or Control properties can be set either at design-time or at run-time. Typically, a property which is dynamic is set at run-time and the more static ones at design-time. Name property of a UserForm can be set only at design-time and cannot be set at run-time. Though you can add, name and set properties of controls at run-time, these are mostly done at design-time itself, as these usually remain static while running a procedure. You might face some complications in adding controls and setting properties at run-time, hence only occasionally do you need to set properties at run-time to appropriately cope with a situation.

Setting control properties with vba:

If the code is in a procedure in the Code Module of the UserForm, use the vba syntax:   Controlname.Property = Setting/Value

If the code is in a Standard Module or in the Code Module of a different UserForm, use vba syntax:   UserFormName.Controlname.Property = Setting/Value

Examples of VBA Syntax:

Label1.Font.Name = «Arial»; Label1.ForeColor = RGB(255, 255, 0); OptionButton1.BackColor = 255; CheckBox1.Value = False; CheckBox1.Alignment = fmAlignmentLeft; TextBox1.MultiLine = True; TextBox1.WordWrap = True; TextBox1.ScrollBars = 2; OptionButton1.AutoSize = True; Me.TextBox1.Enabled = False; TextBox1.TextAlign = fmTextAlignLeft; TextBox1.Text = «Hello»; CommandButton1.Left = 50; TextBox1.MaxLength = 5;  Note: Label1, TextBox1, CheckBox1, OptionButton1 & CommandButton1 are the Control names.

_______________________________________________________________________________

Basic Properties common to the UserForm and most Controls

Name Property

Use the Name property to specify a name for a control or to specify the font name (used in the text portion of a control). Name property of a UserForm can be set only at design-time and cannot be set at run-time. Name property for controls can be set either at design-time or at run-time, BUT if a control is added at design-time, its name cannot be changed at run-time. Typically, the default name of the first CheckBox created is CheckBox1, the default name of the second CheckBox will be CheckBox2, and so on, and similalry for other controls too. The default name of the first Userform you have created will be «UserForm1» (Image 1).

By clicking on «Name» in the Properties Window, you can edit the name. The name should begin with a letter, can have any combination of letters, numbers or underscores, cannot have spaces or symbols and can have a maximum length of 40 characters. It might be a good idea to have a 3-letter prefix in lower case, for each name, to identify and associate with its respective control. The characters following the prefix can start with a capital, for easier readibility. Typically, prefix used for different controls are: frm for UserForm; lbl for Label; txt for TextBox; cmb for ComboBox; lst for ListBox; chk for CheckBox; opt for OptionButton; fra for Frame; cmd for CommandButton; tbs for TabStrip; rfe for RefEdit; and so on.

Syntax for Font:  Font.Name = String

Syntax for all other controls and objects:  object.Name = String

The Name Property is applicable to the UserForm and to all controls.

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

Caption Property

Caption is the text which describes and identifies a UserForm or Control. Typically, the default name and Caption of the first CheckBox created at design-time is CheckBox1, the default name and Caption of the second CheckBox will be CheckBox2, …; default name and caption of the first OptionButton is OptionButton1, …; default name and caption of the first CommandButton is CommandButton, …; and so on. The default caption of the first Userform you have created will be «UserForm1» (Image 1). By clicking on Caption in the Properties Window, you can edit the same, in its right column. The Caption will display in the header of the Userform; in re of Label, CommandButton & ToggleButton controls, Caption is the text which appears on the control; in re. of Tab and Page objects Caption is the text that appears on the tab; in re. of CheckBox & OptionButton Caption appears to the side (right or left, as determined by its Alignment property) of the control; in re. of a Frame control Caption appears on the top-left border of the control. Setting the AutoSize property to True (in a control which has both Caption & AutoSize properties), automatically adjusts the control to display the entire caption. Caption can be set in the Properties window or with vba code. Syntax:  object.Caption = String.

Caption property is applicable to the UserForm and controls Label, CheckBox, OptionButton, ToggleButton, Frame, CommandButton, Tab (Tabstrip) and Page (MultiPage).

————————————————————————————————————- 

Size and Position of a Control

Height, Width Properties:

Sets the the height or width, measured in points. You can manually enter the Height and Width in the Properties Window, or when you size a control, the Height and Width properties get updated automatically. For these properties, VBA only accepts values which are greater than or equal to zero. These properties can be set in the Properties window or with vba code. Syntax:  object.Height = Numberobject.Width = Number. You can also resize a control with a mouse in the following manner: select the control -> the  mouse pointer will change to a two-headed arrow when positioned over the control’s handles (adjustment handles) which are in the middle or corner of its side borders -> adjust the horizontal or vertical size by using the appropriate side handles and to change both the horizontal & vertical size simultaneously use the corner handle -> click and drag handle to the required size and then release mouse button.

The Height and Width Properties are applicable to the UserForm and to all controls.

Left, Top Properties:

Left Property sets the distance between the left edge of the control and the left edge of the form that contains it. Top Property sets the distance between the top edge of the control and the top edge of the form that contains it. For a UserForm, the distance set is between the form and the left or top edge of the window that contains it. For both Left and Top properties, distance is set in pixels. You can manually enter the Left and Top properties in the Properties Window or when you move or size a control, the Left and Top properties get updated automatically. If the value of the Left or Top properties is set to zero, the control will appear at the left edge or top edge of the form that contains it, and specifying a value of less than zero in either of these properties will chop a portion of the control which will not remain visible on the form. These properties can be set in the Properties window or with vba code. Syntax:  object.Left = Numberobject.Top = Number. You can also move a control with a mouse in the following manner: select the control -> the  mouse pointer will change to a four-headed arrow when positioned over the control’s border (avoiding the handles used to resize) -> click and drag the control to the required position and then release mouse button.

The Left and Top Properties are applicable to the UserForm and to all controls.

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

Value Property

Determines the selection status of a control or specifies the control’s content. With respect to the controls CheckBox, OptionButton and ToggleButton: an Integer value of -1 means True and indicates that the control is selected; 0 value means False and indicates that the control is cleared; and the Null value indicates that the control is neither selected nor cleared, and will appear shaded in this case. For the controls ScrollBar and SpinButton, it indicates their current value, which is an integer between maximum and minimum values specified in the Max and Min properties. 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). For a CommandButton, it is a Boolean value which indicates whether the control has been chosen — default setting is False and setting it to True (can be done only with vba code) will invoke the button’s Click event. For a MultiPage, the Value property is set (can be done only with vba code) with an Integer which indicates the current (active) page, and pages are numbered starting from zero (0) which is the first page so that the maximum value is one less than the number of pages. For a TextBox, it refers to the text in the text box. Value property can be set in the Properties window (except for CommandButton and MultiPage controls) or with vba code. Syntax:  object.Value = Variant.

The Value property is applicable to all controls except Label, Frame and Image.

____________________________________________________________________________

Other Properties common to the UserForm and most Controls

These properties can be set in the Properties window or with vba code, unless specified otherwise.

Accelerator Property:

Sets the key to access a control — it is referred to as the accelerator key or access key. This key is a single character, pressed in combination with and after the Alt key. It is used as a short-cut and gives focus to a control and initiates the Click event. In case multiple characters are entered as its value, the first character becomes the value of Accelerator. To click the ‘Enter’ command button in a form, the accelerator key can be set as letter «E» and used by pressing Alt+E. In case the accelerator is set for a Label, then the control which follows Label next in the tab order receives focus (but not initiation of the Click event) instead of the Label itself. Note: The character used as the value of accelerator is key-sensitive, meaning that setting the accelerator key as letter P is the same as letter p or the character + is the same as = because they are entered by pressing the same key.

Accelerator property is applicable to the controls Label, CheckBox, OptionButton, ToggleButton, CommandButton and MultiPage. 

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

Alignment Property:

Specifies how a caption will appear relative to the control. There are 2 settings: (i) fmAlignmentLeft (value 0) — caption appears to the left of the control; and (ii) fmAlignmentRight (value 1) — this is the default setting wherein the caption appears to the right of the control. Note 1: Though ToggleButton has Alignment as one of its properties, it is disabled and Alignment cannot be specified for the ToggleButton. Note 2: The caption text is always left-aligned.

Alignment property is applicable to the controls CheckBox, OptionButton and ToggleButton.

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

AutoSize Property:

A Boolean value (True/False) which specifies if or not the control resizes automatically for its entire contents to be displayed. Setting AutoSize to TRUE automatically resizes the control while setting AutoSize to FALSE (Default option) keeps the size of the control constant wherein content exceeding the control’s area get cut. For the controls TextBox and ComboBox, AutoSize applies to displayed text; for the Image control, AutoSize applies to the displayed image; while for other controls AutoSize applies to the caption. Settings 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 property is applicable to the controls Label, TextBox, ComboBox, CheckBox, OptionButton, ToggleButton, CommandButton, Image and RefEdit.

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

BackColor Property:

Sets the background color for UserForm and controls. The BackStyle property (in re of controls) should be set to fmBackStyleOpaque for the BackColor to have any effect.

BackColor Property applies to all controls (for MultiPage the property can be set only with vba code) and UserForm.

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

BackStyle Property:

Determines whether the background of Controls will be Opaque or Transparent. Sets the background style for an object. It has two settings: (i) fmBackStyleTransparent (value 0) for transparent background, wherein everything behind the control on a form is visible; (ii) fmBackStyleOpaque (value 1) for opaque background, wherein nothing is visible behind the control on a form, and this is also the default. The BackStyle property (for controls) should be set to fmBackStyleOpaque for the BackColor to have any effect.

BackStyle is applicable to the controls Label, TextBox, ComboBox, CheckBox, OptionButton, ToggleButton, CommandButton, Image and RefEdit.

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

BorderColor Property:

Sets the border color for UserForm and Controls. Unless the BorderStyle Property sets a border (ie. it should be a non-zero value, which means other than fmBorderStyleNone), this property will have no effect. BorderStyle defines the border colors using the BorderColor Property while the SpecialEffect property exclusively uses system colors (which are part of the Control Panel for Windows OS) to define its border colors.

BorderColor is applicable to UserForm and the controls Label, TextBox, ComboBox, ListBox, Frame, Image and RefEdit.

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

BorderStyle Property:

Specifies the type of border for an object (control or a form). It has two settings: (i) fmBorderStyleNone (value 0) for no border; (ii) fmBorderStyleSingle (value 1) for a single-line border. UserForm, Label, TextBox, ComboBox, ListBox and Frame have the default value of 0 whereas the default value for an Image is 1. BorderStyle defines its border colors using the BorderColor Property. Note: You cannot simultaneously use both the BorderStyle and SpecialEffect properties to specify the border for a control — specifying a non-zero property for either one will automatically set the other property to zero. And, if the SpecialEffect property for a Frame is set to zero (ie. Flat), the BorderStyle property is ignored.

BorderStyle is applicable to UserForm and the controls Label, TextBox, ComboBox, ListBox, Frame, Image and RefEdit.

————————————————————————————————————- 

ControlSource Property:

Mentions a cell or field (viz. worksheet range in Excel) which is used to set or store the Value property of a control. Changing the value of the control will automatically update the linked cell and a change in the linked cell will update the value of the control. Where A1 is entered in a ControlSource property of a CheckBox, and if cell A1 in ActiveSheet contains TRUE, the CheckBox will appear selected on activating the form and if you deselect the CheckBox, cell A1 will change to FALSE. In a ListBox where the ControlSource mentions Sheet3!D2, the value in the BoundColumn of the selected row will get stored in cell D2, Sheet3. In a TextBox where the ControlSource mentions Sheet3!F2, the text or value in the TextBox will get stored in the worksheet cell Sheet3!F2 and if the cell Sheet3!F2 contains any text, this will appear in the TextBox on activation of UserForm. The default value is an empty string which indicates that no ControlSource Property has been set. Note: To set ControlSource property in Properties window, enter without inverted commas: =Sheet3!F2, and to set with vba code: .ControlSource = «=Sheet3!F2» or .ControlSource = «Sheet3!F2».

ControlSource property is applicable to the controls TextBox, ComboBox, ListBox, CheckBox, OptionButton, ToggleButton, ScrollBar and SpinButton.

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

ControlTipText Property:

Specifies the text displayed when the user holds the mouse over a control. It is useful in giving tips or clarifications to the user on using the control. The default value is an empty string which indicates that no text will be displayed.

ControlTipText Property is applicable to all controls.

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

Enabled Property:

A Boolean value (True/False) which specifies whether the control can be accessed through a vba code and can respond to user-generated events (ie. the user can interact with the control by using mouse, keystrokes, accelerators, or hotkeys). Default value is True, which indicates that the control can be accessed whereas a False value indicates that the user cannot interact with the control. The control is usually accessible through a code even in the case the value is set to False. If Enabled is set to False, the control appears dimmed (except for Image). If Enabled is set to False for a UserForm or a Frame, all controls they contain also get disabled. Enabled Property of a TextBox is particularly useful where you do not want to allow the user to type directly into the TextBox but should be filled only per the user-selected option, say from a ListBox.

Enabled Property applies to all controls and UserForm.

———————————————————————————————————- 

Locked Property:

A Boolean value (True/False) which specifies whether the control is editable or not. True value indicates uneditable, while the default value is False wherein the control can be edited.

Locked property is applicable to the controls TextBox, ComboBox, ListBox, CheckBox, OptionButton, ToggleButton, CommandButton and RefEdit.

Using the Enabled and Locked Properties in conjunction:

1. Enabled is True and Locked is False: the control responds to user-generated events and appears normally; data can be copied and edited in the control.

2. Enabled is True and Locked is True: the control responds to user-generated events and appears normally; data can be copied but not edited in the control.

3. Enabled is False (irrespective of Locked value): the control cannot respond to user-generated events and also appears dimmed; data can neither be copied nor edited in the control.

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

Font Object:

Determines the type of font used in a control or form. You can specify the font name, set the font style (Regular, Italic, Bold, …), underline or strikeout text, and adjust the font size. For the controls TextBox, ComboBox and ListBox, the font of displayed text is set, while for other controls the caption font is set. Note: Setting Font of a UserForm will automatically set the Font of all controls if entered post the UserForm setting but will not change the Font of these controls if they were already present for which you will need to reset Font of each individual control separately. Font property for a MultiPage control can be used only with vba code.

Font applies to UserForm and all controls except ScrollBar, SpinButton and Image.

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

ForeColor Property:

Specifies the foreground color ie. color of displayed text. In respect of Font controls, ForeColor determines the text color; in a Frame, ForeColor determines its caption color; in a ScrollBar or SpinButton, ForeColor determines the color of the arrows. Note: Setting ForeColor of a UserForm will automatically set the ForeColor of controls Label, CheckBox, OptionButton, Frame, MultiPage and TabStrip if entered post the UserForm setting and but will not change the ForeColor of these controls if they were already present for which you will need to reset ForeColor of each individual control separately. ForeColor property for a MultiPage control can be used only with vba code.

ForeColor Property applies to UserForm and all controls except Image.

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

MouseIcon Property:

Assigns an image to a control which gets displayed when the user moves the mouse across that control. Image is assigned by specifying the path and filename of the file it is in. To use the MouseIcon property it is required that the MousePointer property is set to fmMousePointerCustom (value 99).

MouseIcon property is applicable to UserForm and all controls, except MultiPage.

——————————————————————————————————- 

MousePointer Property:

Specifies what type of mouse pointer will be visible when the user moves the mouse over a control. There are 15 settings: (i) fmMousePointerDefault (value 0) — standard pointer, and default value; (ii) fmMousePointerArrow (value 1) — arrow; (iii) fmMousePointerCross (value 2) — Cross-hair pointer; (iv) fmMousePointerIBeam (value 3) — I-Beam; (v) fmMousePointerSizeNESW (value 6) — two-headed arrow pointing northeast and southwest; (vi) fmMousePointerSizeNS (value 7) — two-headed arrow pointing north and south; (vii) fmMousePointerSizeNWSE (value 8) — two-headed arrow pointing northwest and southeast; (viii) fmMousePointerSizeWE (value 9) — two-headed arrow pointing west and east; (ix) fmMousePointerUpArrow (value 10) — up arrow; (x) fmMousePointerHourglass (value 11) — hourglass; (xi) fmMousePointerNoDrop (value 12) — circle with a diagonal line, appearing as a «Not» symbol indicating an invalid control; (xii) fmMousePointerAppStarting (value 13) — arrow and hourglass; (xiii) fmMousePointerHelp (value 14) — arrow and question mark; (xiv) fmMousePointerSizeAll (value 15) — four-headed arrow, pointing north, south, east, and west; and (xv) fmMousePointerCustom (value 99) — image specified by the MouseIcon property.

MousePointer property is applicable to UserForm and all controls, except MultiPage.

——————————————————————————————————- 

Picture Property:

Specifies the picture to be displayed on a control. Picture is assigned by specifying the path and filename of the file it is in. To remove the picture, press DELETE on the value of the property (pressing BACKSPACE will not remove). For controls with captions, you can specify the location of the picture by using the PicturePosition property. For other controls and UserForm, use PictureAlignment Property to specify the location (identifies the control corner to display or at the center) of the picture and use PictureSizeMode Property to specify how (size, scale, strech or enlarge mode) to display the picture.

Picture property is applicable to UserForm and the controls Label, CheckBox, OptionButton, ToggleButton, Frame, CommandButton, MultiPage and Image.

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

PicturePosition Property:

Specifies where the picture appears in the control vis-a-vis its caption. The alignment of the picture with its caption is determined by this property. There are 13 settings in a format where the string fmPicturePosition is followed by the location of the picture relative to its caption and next is the alignment of the caption relative to the picture, viz. fmPicturePositionLeftTop — the picture appears to the left of the caption and the caption is aligned with the top of the picture; and so on. The last setting is fmPicturePositionCenter — both the picture and caption are centered in the control and the caption is on top of the picture. Default is fmPicturePositionAboveCenter (value 7) — the picture appears above the caption and the caption is centered below the picture. In the absence of a caption, the picture’s location is relative to the center of the control. If no picture is specified to be displayed, the PicturePosition property will have no effect.

PicturePosition property is applicable to the controls Label, CheckBox, OptionButton, ToggleButton and CommandButton.

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

SpecialEffect Property:

Determines how the control visually appears. For a CheckBox, OptionButton, or ToggleButton, the two settings are: (i) fmButtonEffectFlat (value 0); and (ii) fmButtonEffectSunken (value 2) — Default for CheckBox and OptionButton. For other applicable controls the five settings are: (i) fmSpecialEffectFlat (value 0) — Default for UserForm and the controls Image and Label; (ii) fmSpecialEffectRaised (value 1); (iii) fmSpecialEffectSunken (value 2) — Default for controls TextBox, ComboBox and ListBox; (iv) fmSpecialEffectEtched (value 3) — Default for Frame; and (v) fmSpecialEffectBump (value 6). The visual appearance of each setting is self-explanatory viz. visual effect can be Flat, Raised, Sunken, Etched and Bump. Note 1: Though ToggleButton has SpecialEffect as one of its properties, it is disabled and SpecialEffect cannot be specified for the ToggleButton. Note 2: You cannot simultaneously use both the BorderStyle and SpecialEffect properties to specify the border for a control — specifying a non-zero property for either one will automatically set the other property to zero. And, if the SpecialEffect property for a Frame is set to zero (ie. Flat), the BorderStyle property is ignored. Note 3: SpecialEffect property exclusively uses system colors (which are part of the Control Panel for Windows OS) to define its border colors.

SpecialEffect property is applicable to UserForm and the controls Label, TextBox, ComboBox, ListBox, CheckBox, OptionButton, ToggleButton, Frame, Image and RefEdit.

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

TabIndex Property:

TabIndex is the position of the control in a UserForm’s tab order (when the user presses the Tab key). The Index value is expressed as an Integer, with 0 being the first position in the tab order and the highest possible Index value will be one less than the number of controls in the form, to which the TabIndex property is applicable. Entering an Index value less than zero will give an error, a value greater than the highest possible will reset it to the highest value, and each control will have a unique Index value. TabIndex property for a MultiPage control can be used only with vba code.

TabIndex is applicable to all controls except Image.

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

TabStop Property:

A Boolean value (True/False) which specifies whether the control can be selected with the tab key. The True value is the default, and sets the control as a tab stop. The False value ignores the control during user tabs but its position in the tab order (as specified in the TabIndex property) remains intact. TabStop property for a MultiPage control can be used only with vba code.

TabStop is applicable to all controls except Label and Image.

——————————————————————————————————-

Visible Property:

A Boolean value (True/False) which is set to make a control visible or hidden. Default value is True, wherein control is visible. This property is particularly useful wherein on satisfaction of a condition you can activate a hidden control which otherwise you might not want to appear in the UserForm viz. show or hide a message dependent on total marks received in a test.

Visible Property applies to all controls.

——————————————————————————————————-

WordWrap Property:

A Boolean value (True/False) which specifies whether the text of a control will wrap to the next line. Default value is True, wherein the text wraps. If MultiLine property of a control is set to False, WordWrap is ignored (in controls which support both these properties viz. TextBox).

WordWrap property is applicable to the controls Label, TextBox, CheckBox, OptionButton, ToggleButton, CommandButton and RefEdit.

____________________________________________________________________

Specifying Color in Properties Window

To enter or change color, in the property’s right column (in Properties Window) click the «Palette» tab and select a new color, or select a predefined color from the «System» tab. It can also be entered as a Long Integer which represents a valid color (this is the decimal format). Alternatively, the color can be entered in hexadecimal notation. The Properties Window displays values in Hexadecimal format, even if the color is entered in decimal format.

Long Integer as Color: Excel color can be represented as a Long Integer, the integer value being derived from the vba RGB function viz. «RGB(Red, Green, Blue)». In the RGB function, the value of each color component of Red, Green & Blue is in the range of 0 to 255. A Long Integer can be derived from the RGB function as shown below:

RGB Function Deriving Integer Value Long Integer Web/HTML Hexa-decimal (RRG GBB) VBA Hexa-decimal (BBG GRR) Color
RGB(1,0 ,0) =1*1+ 0*256+ 0*65536 1 010000 000001 Black (vari-ation)
RGB(0,1 ,0) =0*1+ 1*256+ 0*65536 256 000100 000100 Black (vari-ation)
RGB(0,0 ,1)  =0*1+ 0*256+ 1*65536  65536 000001  010000  Black (vari-ation) 
RGB(255, 0,0)  =255*1+ 0*256 + 0*65536  255 FF0000  0000FF  Red 
RGB(0, 255,0)  =0*1+ 255*256 + 0*65536  65280 00FF00  00FF00  Green 
RGB(255, 255, 255) =255*1+ 255*256+ 255* 65536  16777215 FFFFFF  FFFFFF  White 
RGB(0,0 ,0)  =0*1+ 0*256 + 0*65536  0 000000  000000  Black 
RGB(255, 255,0)  =255*1+ 255*256 + 0*65536  65535 FFFF00  00FFFF  Yellow 
RGB(255, 0,255)  =255*1+ 0*256 + 255* 65536  16711935 FF00FF  FF00FF  Magenta 
RGB(0,0, 255)  =0*1+ 0*256+ 255* 65536  16711680 0000FF  FF0000  Blue 
RGB(10, 255,255)  =10*1+ 255*256 + 2255* 65536  16776970 0AFFFF  FFFF0A  Aqua (vari-ation) 

Hexadecimal notation for Color:

In hexadecimal format numbers are expressed in base-16 notation. There are 16 hexadecimal digits. The first 10 are the same as decimal digits viz. 0 to 9, and then the six letters A to F in place of decimals 10 to 15. Hence, 16 different values can be represented by a single hexadecimal digit whereas these would be 10 for a decimal digit, making it more compact because values can be represented in fewer digits. Colors are derived from 3 color components of Red, Green & Blue and each component can take a value from 0 to 255 and the corresponding hexadecimal representation is from 00 to FF. FF is the largest hex number, equating to the decimal value of 255. In hexadecimal, color is represented by six characters. In web and HTML programming, hex notation is in the format of RRGGBB (coded as #RRGGBB viz. RRGGBB prefixed with #), wherein the first two characters represent Red, the next two represent Green and the last two represent Blue viz. RRGGBB. The red color represented by RGB function of RGB(255,0,0) equates to integer value of 255 and to hexadecimal notation of FF for the red color and 00 for green and 00 for blue ie. «FF0000». New colors can be derived by mixing the basic 3 color values viz. get yellow from mixing red and green (255,255,0) which equates to integer value 65535 and to hexadecimal notation of «FFFF00». Get Magenta color by mixing red and blue (255,0,255) which equates to integer value 16711935 and to hexadecimal notation «FF00FF». Color tone can be changed wherein «FF77FF» (increasing intensity of green) will be a lighter magenta and «FF00FF» (decreasing intensity of green) will be a darker shade of magenta.

The VBA Hex function «Hex(number)» returns a string representing the hexadecimal value of a number. Hex function converts a decimal format to a hex notation. Converting a number to hex format with the Hex function viz. Hex(255), will return «FF», representing the color Red. It should be prefixed with &H and then («&HFF») entered in the Properties Window (right column), wherein it will appear as «&H000000FF&». Hex notation is always prefixed with &H, which indicates it is being used. The trailing ampersand (&) tells vba it’s a Long value/data type (4 byte) and not a 2-byte Integer data type, and has nothing to do with hexadecimal notation. Note: Instead of the RRGGBB notation (used in web and HTML programming) VBA uses BBGGRR notation, or &H00BBGGRR&. The Hex function also returns in BBGGRR notation. This explains why the color red appears as &H000000FF& in the Properties window whereas its html hexadecimal notation is FF0000 viz. RGB(255,0,0) using the RGB function. Using another example for color blue represented by RGB(0,0,255): this equates to integer value of 16711680 (=0*1+0*256+255*65536), and using the Hex function, Hex(16711680) returns FF0000 whereas the web/html hexadecimal notation of color blue RGB(0,0,255) is 0000FF. The hex notation displayed in the Properties Window (VB editor) is in BBGGRR format: &H00FF0000&.

Four ways to specify color in Properties Window — (i) in the property’s right column (in Properties Window) click the «Palette» tab and select a new color; (ii) select a predefined color from the «System» tab; (iii) enter a Long Integer which represents a valid color; or (iv) enter the hexadecimal notation in BBGGRR format preceded by &H. The hex notation displayed will be in BBGGRR format, viz. &H00FFFF0A& for aqua (variation of aqua) color.

_____________________________________________________________________

Applicability of Properties to UserForm and its Controls — A SnapShot:

 

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!

Like this post? Please share to your friends:
  • Excel vba commandbar controls
  • Excel vba combobox1 list
  • Excel vba combobox ячейка
  • Excel vba combobox список значений
  • Excel vba combobox очистить список