UserForms are custom dialog boxes that allow you to create professional interfaces for your Excel applications. They provide a way to interact with users, collect input, and display information in a more controlled and visually appealing way than standard message boxes or input boxes.
To create a UserForm in the Excel VBA 365 editor:
When you create a UserForm, the Toolbox appears automatically. This contains all the controls you can add to your form:
This example shows how to display information from your worksheet in a ListBox control on a UserForm. The ListBox can show multiple columns of data with headers.
Private Sub CommandButton1_Click()
' Set ListBox to display 2 columns
ListBox1.ColumnCount = 2
' Show column headers
ListBox1.ColumnHeads = True
' Define the data range (A2:B5 on Sheet1)
ListBox1.RowSource = "Sheet1!A2:B5"
End Sub
This example demonstrates how to create a basic calculator that takes input from text boxes and displays the result both on the form and in the worksheet.
Setup Instructions:
Code for the Calculate Button:
Private Sub CommandButton1_Click()
' Calculate sum and display in Label
Label1.Caption = Val(TextBox1.Text) + Val(TextBox2.Text)
' Write result to cell C1
Cells(1, 3).Value = Label1.Caption
End Sub
This advanced example shows how to create a data entry form with input validation.
Private Sub cmdSubmit_Click()
' Validate input
If txtName.Text = "" Then
MsgBox "Please enter a name", vbExclamation
txtName.SetFocus
Exit Sub
End If
If Not IsNumeric(txtAge.Text) Then
MsgBox "Age must be a number", vbExclamation
txtAge.SetFocus
Exit Sub
End If
' Add data to worksheet
Dim nextRow As Long
nextRow = Worksheets("Data").Cells(Rows.Count, 1).End(xlUp).Row + 1
With Worksheets("Data")
.Cells(nextRow, 1).Value = txtName.Text
.Cells(nextRow, 2).Value = txtAge.Text
.Cells(nextRow, 3).Value = IIf(chkMember.Value, "Yes", "No")
End With
' Clear form for next entry
ClearForm
MsgBox "Data saved successfully!", vbInformation
End Sub
Private Sub ClearForm()
txtName.Text = ""
txtAge.Text = ""
chkMember.Value = False
txtName.SetFocus
End Sub
In the next lesson, we'll explore Excel VBA Objects - the building blocks of VBA programming that let you control every aspect of Excel.
Copyright ® 2023 Dr.Liew Voon Kiong . All rights reserved [Privacy Policy]
Contact: Facebook Page