×

VBA Creating, Displaying, Uploading UserForms

UserForm is a customized interface and acts as a VBA container and can add various controls as per the required functionality, each of which has certain usage and related properties. You can create your own dialog boxes with this feature. Your project can have n number of userforms wherein each userform has its own dialog own.

Creating a Userform

There are two ways to install a UserForm in VBA, which are as follows. 

Process 1: Right Click on VBAProject ->Click on insert -> Click on Userform.

VBA Creating, Displaying, Uploading UserForms

Process 2: Click on Insert from the ribbon bar-> Click on Userform.

VBA Creating, Displaying, Uploading UserForms

In both the process, you will notice a folder has been introduced with name Forms (inside which it consists the UserForm) in the VBA Project. Further clicking on the UserForm will straightway lead you to a window entitled UserForm1 (though the name can be changed from the properties) following with a “controls” toolbox.

VBA Creating, Displaying, Uploading UserForms

Adding control to Userform

Controls are added to a UserForm to accept the inputs from the user and make it more user-friendly. The control box can be resized by stretching the adjustment handles and can be dragged to any position. You can even adjust the spacing and the alignment of the UserForm. There are two ways to add the controls to your useform:

  • Select the required control and drag it to the Userform. 
  • The Second method is to left-click on the control available in the ToolBox, in the form left-click, and the control will be automatically added.

Example: Create a VBA userform, which takes the basic information from the user and update it on the excel sheet. Refer to the below image to get a glimpse of the form.

VBA Creating, Displaying, Uploading UserForms
Private Sub UserForm_Initialize()
 'Setting the values for each form control. The UserForm gets loaded wherever the program is run. 
 Dim i As Integer
 Dim myArray As Variant
 'in the list box setting the age values and categorizing them from 17 to 50.
 With Me.ListBox1
 For i = 17 To 50
 .AddItem i & " yrs"
 Next i
 End With
 'adding the cities into combo box
 myArray = Array("Mumbai", "Banglore", "Delhi", "Noida", "Gurugram", "Chennai", "Kolkata", "Patna", "Hyderabad", "Ahmedabaad")
 Me.ComboBox1.List = myArray 
 ‘so as only one option could be selected
 OptionButton1.GroupName = "Gender"
 OptionButton2.GroupName = "Gender"
 ‘disabling the text field for the spouse so it can only work if the user has checked the married checkbox
 Me.spouse_name.Enabled = False
 End Sub
 ‘double click on the married checkbox the write the following code in the sub procedure
 Private Sub CheckBox1_Click()
 'user can only enter in spouse_name TextBox if the CheckBox is selected
 If CheckBox1.Value = True Then
     spouse_name.Enabled = True
 Else
     spouse_name.Enabled = False
 End If
 End Sub
 ‘double click on the clear button and write the following code in sub procedure
 Private Sub CommandButton2_Click()
   ‘clearing the value of name text box
 TextBox1.Value = ""
 spouse_name.Value = ""
 'clearing the value for OptionButton  "Male"
 OptionButton1.Value = False
 'clearing the value for OptionButton  "Female"
 OptionButton2.Value = False
 'clearing the ListBox value for Age selection
 ListBox1.ListIndex = -1
 'clearing the values in ComboBox for Country 
 ComboBox1.Value = ""
 'CheckBox to select if Married
 CheckBox1.Value = False
 End Sub
 ‘double click on the save button and type the following code in the sub procedure
 Private Sub CommandButton1_Click()
 Dim totalRows As Long
 Dim str As String
 Dim endDate As String, startDate As String
 'error check - blank UserForm fields not permitted 
 If TextBox1.Text = "" Then
 MsgBox "Name can’t be black", vbOKOnly, "Name Error!"
 Exit Sub
 ElseIf OptionButton1.Value = False And OptionButton2.Value = False Then
 MsgBox "Gender can’t be blank!", vbOKOnly, "Gender Error!"
 Exit Sub 
 ElseIf ListBox1.ListIndex = -1 Then
 MsgBox "Age can’t be blank!", vbOKOnly, "Age Error!"
 Exit Sub
 ElseIf ComboBox1.Value = "" Then
 MsgBox "Country can’t be blank!", vbOKOnly, "Country Error!"
 Exit Sub
 ElseIf CheckBox1.Value = True And spouse_name.Text = "" Then 
 MsgBox "Spouse Name can’t be blank", vbOKOnly, "Spouse Error!"
 Exit Sub
 End If
  ‘finding the last entered row
 totalRows = Sheet1.Cells(Rows.Count, "A").End(xlUp).Row
 If totalRows < 3 Then
 totalRows = 3
 Else
 totalRows = totalRows
 End If
 ‘copying the form values in the excel sheet:
 Sheet1.Cells(totalRows + 1, 1) = TextBox1.Text
 If OptionButton1.Value = True Then
 Sheet1.Cells(totalRows + 1, 2) = "Male"
 ElseIf OptionButton2.Value = True Then
 Sheet1.Cells(totalRows + 1, 2) = "Female"
 End If
 Sheet1.Cells(totalRows + 1, 3) = ListBox1.Value
 If spouse_name.Text <> "" Then
 Sheet1.Cells(totalRows + 1, 4) = spouse_name.Text
 Else
 Sheet1.Cells(totalRows + 1, 4) = "Unmarried"
 End If
 Sheet1.Cells(totalRows + 1, 5) = ComboBox1.Value
 'arranging and sorting all the data stored in excel sheet1, by name in alphabetic order
 Sheet1.Range("A4:H" & totalRows + 1).Sort Key1:=Sheet1.Range("A4"), Order1:=xlAscending
 'Clearing all the text
 TextBox1.Value = ""
 spouse_name.Value = ""
 OptionButton1.Value = False 
 OptionButton2.Value = False
 ListBox1.ListIndex = -1
 ComboBox1.Value = "" 
 CheckBox1.Value = False
 End Sub 

Output

Case 1: Fill all the details and press the save button. The excel sheet will be update with the inserted values. Repeat it two three times and you notice the names are present in the sorted order.

VBA Creating, Displaying, Uploading UserForms
VBA Creating, Displaying, Uploading UserForms

Case 2: Keep any field unfilled, and you will notice and message error pops out notifying that blank field can’t be entertained.

VBA Creating, Displaying, Uploading UserForms

Related Topics

VBA VBScript Regex Methods Regex

VBA VBScript Regex Methods Regex The VBA Regex supports 3 methods which are as follows: ExecuteReplaceText Execute The execute method is used to extract a match from the given based on the defined matching...

3 minutes read.

Excel VBA LTrim Function

VBA LTrim Function: The LTrim function in VBA removes the leading spaces from a supplied text string. Syntax LTrim (String) Parameter String (required) - This parameter represents he text string that you want to remove...

1 minute read.

Scope in Visual Basics

Definition of Scope The scope of any programming language implies the area of code where the variables will be identified, accessed, and used. Every variable has a scope associated with it. The scope of...

4 minutes read.

VBA Regex Pattern Validation

VBA Regex Pattern Validation The key purpose of using Regex in VBA was to validate the data and extract the same category of data. There are certain formats that are standard...

6 minutes read.

Excel VBA RTrim Function

VBA RTrim Function: The Rtrim function in VBA removes the leading spaces from the text in the specified string. Syntax RTrim (String) Parameter String (required) – This parameter represents the string from which you want...

1 minute read.

Excel VBA Filter Function

VBA Filter Function: The Filter function in VBA returns a subset for the given string array, based on specified criteria. Syntax Filter (SourceArray, Match, [Include], [Compare]) Parameter SourceArray (required) – This parameter the array of Strings that you...

2 minutes read.

Excel VBA Tan Function

VBA Tan Function: The Tan function in VBA returns the tangent for the specified angle in radians. Syntax Tan (Number) Parameter Number (required) – This parameter represents the angle supplied in radiant that you want...

1 minute read.

Excel VBA Mid Function

VBA Mid Function: The Mid function in VBA returns a substring from within a supplied string. Syntax Mid (Str, Start, [Length]) Parameter Str (required) -This parameter represents a string from which you want to extract the substring. Start...

1 minute read.

Excel VBA DateDiff Function

The DateDiff function in VBA returns a Long data value representing the number of intervals between two specified dates/times where the type of interval is supplied by the user. Syntax DateDiff (Interval, Date1, Date2, [FirstDayOfWeek], [FirstWeekOfYear]) Parameter Interval (required)...

2 minutes read.

Excel VBA Sqr Function

VBA Sqr Function: The Sqr function in VBA returns the square root for the specified number. Syntax Sqr (Number) Parameter Number (required) – This parameter represents a positive numeric value that you want to calculate...

1 minute read.

Excel VBA ABS Function

VBA ABS Function: The ABS function in VBA returns the absolute value of the specified number. Syntax Abs (Number) Parameter Number (required) – This parameter represents the number that you want the absolute value of. Return This...

1 minute read.

VBA Dim

What is Dim? DIM or Dimension or Declare in Memory is a keyword that is used in VBA to declare a variable with the different data types (Integer, String, variable, Boolean, Double, etc.)...

7 minutes read.

Excel VBA Asc Function

VBA Asc Function: The Asc function in VBA returns an integer showing the character code for the first character of a given string. Syntax Asc (String) Parameter String (required) – This parameter represents the text...

1 minute read.

Introduction to Visual Basic Editor Window

How to enable the Developer Ribbon Tab? In order to work with VBA, users need to make a small change in Excel to display a new tab (Developer) at the top of the...

5 minutes read.

Excel VBA IsDate Function

VBA IsDate Function: The IsDate function in VBA returns a Boolean value indicating whether the given expression is interpreted as a VBA Date or not. Syntax IsDate (Expression) Parameter Expression (required) – This parameter...

1 minute read.

Excel VBA Hour Function

The hour function in VBA returns the hour element for the specified time. Syntax Hour (Time) Parameter Time (required) – This parameter represents the time. Return This function returns the hour element for the specified time. Example 1 Sub HourFunction_Example1() ...

1 minute read.

Basics of Userform

A User Form is a built-in customized dialog box that fetches data from the user through a user-friendly dialog box or window that makes up part of an application's user interface. It...

9 minutes read.

Excel VBA Val Function

VBA Val Function: The Val function in VBA converts the given string into a numeric value. This function ignores spaces and continues to read the characters after space(s). It stops...

1 minute read.

Excel VBA Date Function

VBA Date Function The Date function in VBA returns the current date. Syntax Date( ) Parameter NA Return This function returns the current date. Example 1 Sub DateFunction_Example1() ' retuning the current date in the variable currentDate Dim currentDate As...

1 minute read.

VBA Pivot Table Grouping

VBA- Pivot Table Grouping For an instance, if in our pivot table, we have 11 different age groups from 20 to 30 -  but there might be a possibility that we...

2 minutes read.