×

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 Regex

What is a Regex? Regex stands for Regular Expression is basically a pattern matching strings within another string. They are supported in many languages, including .net, C++, Python, etc. They are...

5 minutes read.

Excel VBA Len Function

VBA Len Function: The Len function in VBA returns the number of characters in a supplied string or the number of bytes required to store a supplied variable. Syntax Len (Expression) Parameter Expression (required)-...

1 minute read.

VBA Subscript out of Range

What is Subscript out of Range? The VBA Subscript out of Range error (which is also called as Run-Time Error 9) mostly triggers when the user selects any cell, sheet, or workbook which does...

5 minutes read.

VBA Charts

What is a Chart? A chart is used to visually show numbers or data in a spreadsheet (or spread over multiple spreadsheets) so that the end-user can look at the chart...

3 minutes read.

Excel VBA MonthName Function

Excel VBA MonthName Function: The MonthName function in VBA returns a string with the month name for the specified month number. Syntax MonthName (Month, [Abbreviate]) Parameter Month (required) – This parameter represents an integer between...

1 minute 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.

Steps to Create a Chart in VBA

Steps to Create a Chart Charts are created either by directly working with the chart variable object that defines the chart data or by ChartObject method. In order to get to...

3 minutes read.

Excel VBA Weekday Function

Excel VBA Weekday Function: The TimeValue function in VBA returns an integer (1 to 7), signifying the day of the week for the specified date. Syntax Weekday (Date, [FirstDayOfWeek]) Parameter Date (required) – This parameter...

2 minutes read.

Excel VBA TimeValue Function

Excel VBA TimeValue Function: The TimeValue function in VBA returns a Time from the specified String interpretation of a time /date where the date information for the given string is...

1 minute read.

Excel VBA IsObject Function

VBA IsObject Function: The IsObject function in VBA returns a Boolean value showing whether the specified variable represents an Object variable type or not. Syntax IsObject (Expression) Parameter Expression (required)- This parameter represents the...

1 minute read.

Excel VBA LBound Function

Excel VBA LBound Function: The LBound function in VBA returns the lowest subscript for the specified dimension in the given array. Syntax LBound (ArrayName, [Dimension]) Parameter ArrayName (required) – This parameter represents an array for which...

1 minute read.

Excel VBA WeekdayName Function

Excel VBA WeekdayName Function: The WeekdayName function in VBA returns a string containing the weekday name, for the specified integer representation of a weekday. Syntax WeekdayName (Weekday, [Abbreviate], [FirstDayOfWeek]) Parameter Weekday (required) – This parameter represents...

2 minutes read.

Excel VBA Month Function

The Mont function in VBA returns the month number for the specified date. Syntax Month (Date) Parameter Time (required) – This parameter represents the date. Return This function returns the month number for the specified date. Example 1 Sub MonthFunction_Example1() ...

1 minute read.

ActiveX Controls

ActiveX Controls are one of the most used Excel Controls to automate applications with Excel VBA. It has the same controls, unlike Form Controls (Command Button, combo box, checkbox, etc.), but it...

3 minutes read.

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

4 minutes read.

Excel VBA DateValue Function

The DateValue function in VBA returns a VBA Date from the given String representation of a date wherein the time information is ignored. It is unable to interpret dates that include the...

1 minute 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 CVErr Function

VBA CVErr Function: The CVErr function in VBA returns an Error data type, involving with a user-specified error code. Syntax CVErr (Expression) Parameter Expression (required)- This parameter represents the required error code. Return This function returns an...

1 minute 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 User-Defined Functions

User-Defined Functions One of the advantages of VBA is that you can create your own functions using macros. These functions can be called and used as other functions in excel and use them. You can...

3 minutes read.