Excel VBA

Excel UserForm Controls - Label, TextBox and CommandButton

User Rating:  / 10


UserForm Controls - Label, TextBox and CommandButton


Also refer "2. UserForm and Controls - Properties" for properties common to the UserForm and most Controls

Note: In below given examples, vba codes are required to be entered in the Code Module of the UserForm, unless specified otherwise.


Excel VBA UserForms and Controls


1. UserForms in Excel VBA - UserForm Basics; Add Controls dynamically at run-time using the Add Method; UserForm Controls (A Snapshot).

2. UserForm and Controls - Properties.

3. UserForm Controls - Label, TextBox and CommandButton

4. UserForm Controls - ComboBox and ListBox.

5. UserForm Controls - CheckBox, OptionButton and ToggleButton.

6. UserForm Controls - Frame, MultiPage and TabStrip.

7. UserForm Controls - ScrollBar and SpinButton.

8. UserForm Controls - Image and RefEdit.




A Label Control displays text and is used to describe other controls viz. it is often used to describe a TextBox, or if you want to display instructions on the form. Use the Caption property to display text, the Left & Top properties to position it, the TextAlign property to align text within the Label, the Font property for font name/style/size, the BackColor and ForeColor properties for background and text colors. You can format a Label either in the Properties Window or using a VBA statement like Label1.Caption = "Enter brief particulars" or using the vba WITH statement as shown below.

Private Sub CommandButton1_Click()

'clicking the command button in the UserForm will format the Label

With Label1

'to display text        
.Caption = "Enter brief particulars"

'text alignment set to center

.TextAlign = fmTextAlignCenter


'wrap text
.WordWrap = True

'set font property          
.Font.Name = "Arial"

.Font.Size = 12

.Font.Italic = True


'set font color to yellow and background color to red

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

End With

End Sub






A CommandButton is typically used to execute a macro. The Click event of the CommandButton is used to attach vba code to a CommandButton of a UserForm. In VBE (Visual Basic Editor), if the UserForm is visible, you can double-click on the CommandButton to access the Click event, or else you can select the name of the CommandButton (in the code module for the UserForm) from the top-left dropdown of the code window and then select Click from the top-right dropdown. 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. See below example(s):


Example 1 - The Click event which unloads the UserForm on clicking the CommandButton:


Private Sub CommandButton2_Click()
'clicking on the button unloads the UserForm

'display message before closing
MsgBox "Closing UserForm!"

'unloads the UserForm
Unload Me

End Sub



Example 2 - Clicking the CommandButton will call (& execute) another macro whose name has been inserted - used typically when a set of codes are often or repeatedly required to be executed. Refer Images 5a (before Clear Button is clicked) & 5b (after Clear Button is clicked): 



Private Sub CommandButton1_Click()
'clicking on the "Clear" button will call another macro, named clearForm, which will get executed:


End Sub



Private Sub clearForm()
'this macro is called on clicking the "Clear" button - clears all controls in the UserForm:

'clear all text appearing in TextBox
TextBox1.Value = ""

'clear the text area of the ComboBox (ie. user-entered or user-selected value)
ComboBox1.Value = ""

'deselect the CheckBox
CheckBox1.Value = False

'deselect the OptionButton
OptionButton1.Value = False

End Sub






A TextBox accepts text or data from the user. In addition to the common properties mentioned earlier, its key properties include:


AutoTab Property: A Boolean value (True/False) which specifies whether the tab moves automatically to the next control in the tab order after the the maximum allowable number of characters (as determined by the MaxLength property) are entered in the TextBox by the user. False value (is the default) indicates moving manually to the next control in the tab order when the user presses the Tab key. This property is particularly useful in a case where the TextBox accepts a 5-digit item code number and the tab moves on automatically after 5 digits are entered.


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.


MaxLength Property: Specifies the maximum number of characters which can be entered in a TextBox. Specifying a value of 0 indicates there is no maximum limit.


MultiLine Property: A Boolean value (True/False) which determines if text will be displayed in multiple lines or not, in the TextBox. True indicates that the text is displayed in multiple lines, and this is also the default value. See the ScrollBars Property below for how a multiline TextBox can have vertical scroll bars and even a horizontal scroll bar under certain conditions. The WordWrap property is ignored in the single-line setting.


PasswordChar Property: Specifies what characters to display in TextBox instead of the characters actually entered or typed by the user. This property is useful to protect sensitive information or security codes, or to validate a user before allowing to proceed further.


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) - this is the default setting; (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.


Text Property: The text in a TextBox is returned or set by this property. A value assigned to the Text property gets automatically assigned to the Value property, and vice-versa.



Example 1: You can Add a TextBox in a UserForm and format it (ie. apply or set properties), either in the Properties Window, or using VBA code as shown below.


Private Sub CommandButton1_Click()
'click command button to create new TextBox and apply properties - a MultiLine TextBox with a vertical scroll bar

Dim txtSampleTextBox As MSForms.TextBox

Set txtSampleTextBox = Controls.Add("Forms.TextBox.1", "txtSampleTB")

With txtSampleTextBox

'set font property
.Font.Name = "Times New Roman"

.Font.Size = 10


'text alignment set to center
.TextAlign = fmTextAlignLeft


'specify size
.Width = 100
.Height = 50

'set position in the UserForm
.Left = 50
.Top = 75

'set behaviour
.MultiLine = True
.WordWrap = True
.AutoSize = False
.ScrollBars = 2

'set focus

End With

End Sub




Example 2: Enabled Property of a TextBox is particularly useful where 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 - see below vba code(s):


Private Sub UserForm_Initialize()
'set properties for ListBox and TextBox on initialization of UserForm


'populating ListBox with numbers 1 to 10; display a ControlTip instructing the user to select from ListBox.
With ListBox1


For i = 1 To 10

.AddItem i

Next i

.ControlTipText = "Select Number from ListBox, to enter in TextBox."

End With


'set Enabled Property to False so that the user cannot type directly; Note: ControlTip cannot be displayed when Enabled is set to False
Me.TextBox1.Enabled = False

End Sub



Private Sub ListBox1_Click()
'ListBox click event


'fills TextBox on ListBox selection
TextBox1.Text = ListBox1.Value


End Sub




Example 3: Use TextBox to set up a password - set multiple username-password matches to enable multi-user access.



In this Example we use the PasswordChar Property to check if username and password match, in which case the user is allowed to proceed and UserForm1 gets loaded. UserForm2 (Refer Image 6) contains TextBox1 for entering username and TextBox2 for entering password, and CommandButton1 which on being clicked matches the username & password, and on validating a match the UserForm1 is loaded allowing the user to proceed.


Private Sub UserForm_Initialize()
'set properties for TextBox2 on initialization of UserForm2.


'set maximum length for password field
TextBox2.MaxLength = 5

'specify characters displayed in TextBox instead of the characters actually entered
TextBox2.PasswordChar = "*"


'set yellow as background color
TextBox2.BackColor = RGB(255, 255, 0)

End Sub



Private Sub CommandButton1_Click()
'use TextBox to set up a password; click command button to validate password to proceed to UserForm1.

Dim password As String

'set matching usernames and passwords - (Angelina & 12345), (Brad & 23456) & (George & 34567)

If TextBox1.Text = "Angelina" And TextBox2.Text = "12345" Then

password = "True"

ElseIf TextBox1.Text = "Brad" And TextBox2.Text = "23456" Then

password = "True"

ElseIf TextBox1.Text = "George" And TextBox2.Text = "34567" Then

password = "True"

End If


'if username and password match, the user is allowed to proceed and UserForm1 gets loaded:

If password = "True" Then

MsgBox "Password Validated! Please Continue."

Unload Me


'if if username and password do not match, user is requested to try again:


MsgBox "Incorrect UserName/Password. Try Again."

'clear both TextBox

TextBox1.Text = vbNullString

TextBox2.Text = vbNullString

'set focus to TextBox1


End If

End Sub



Bottom Ad

© 2014 GlobaliConnect.com. All rights reserved.