Excel_VBA_Intermediate_Post_Course_Reference
Excel_VBA_Intermediate_Post_Course_Reference
Variables in VBA
Variables are used to store data that your VBA code can manipulate. Think of them as containers that hold information
which can be referenced and manipulated throughout your code.
Declaring Variables
Why declare variables?
Example:
Example:
Procedure-Level (Local) Variables: Declared within a procedure using Dim. Accessible only within that procedure.
Module-Level (Private) Variables: Declared at the top of a module using Private. Accessible to all procedures within that
module.
Public Variables: Declared at the top of a module using Public. Accessible from any module in the project.
Example:
Sub ExampleProcedure()
Dim localVariable As Double
End Sub
Excel VBA Intermediate
Assigning a Value to a Variable
After declaring a variable, you can assign a value to it using the assignment
operator =.
variableName = value
Examples
Example 1: Storing a Number
Sub StoreNumber()
Dim age As Integer
age = 25
MsgBox "Age: " & age
End Sub
In this example, the variable age is declared as an Integer and assigned the value 25. The MsgBox function then displays
the value of age.
Sub StoreText()
Dim name As String
name = "Alice"
MsgBox "Name: " & name
End Sub
Here, the variable name is declared as a String and assigned the value "Alice". The MsgBox function displays the value
of name.
Sub StoreCalculation()
Dim price As Double
Dim quantity As Integer
Dim total As Double
price = 19.99
quantity = 5
total = price * quantity
In this example, price and total are declared as Double, and quantity is declared as an Integer. The total cost is calculated
by multiplying price and quantity, and the result is stored in the total variable.
Sub StoreBoolean()
Dim isActive As Boolean
isActive = True
MsgBox "Is Active: " & isActive
End Sub
Here, the variable isActive is declared as a Boolean and assigned the value True. The MsgBox function displays the
value of isActive.
How do I sort in Excel VBA?
Excel VBA Intermediate
Using Variables in Conditions
Variables can also be used in conditions to control the flow of your program.
Example 5: Using Variables in an If Statement
Sub CheckAge()
Dim age As Integer
age = 18
Exit Sub
ErrorHandler:
Dim errorMessage As String
errorMessage = "An error occurred: " & Err.Description
MsgBox errorMessage
End Sub
You can use this function in Excel by typing =AddNumbers(5, 10) in a cell, which will return 15.
Working with Multiple Arguments
You can create functions that take multiple arguments to perform more complex calculations.
Example 2: Calculating the Area of a Rectangle
Use this function in Excel by typing =RectangleArea(5, 10) to get the area of a rectangle with length 5 and width 10.
Example 3: Calculating the Average of Three Numbers
Use this function in Excel by typing =AverageThreeNumbers(5, 10, 15) to get the average of the three numbers.
Open the Visual Basic for Applications (VBA) editor by pressing Alt + F11.
Insert a new module by clicking Insert > Module.
Copy and paste your function code into the module.
Close the VBA editor.
Use your function in Excel by typing =FunctionName(arguments) in a cell.
Advanced Examples
Example 4: Calculating Compound Interest
Use this function in Excel by typing =CompoundInterest(1000, 0.05, 10) to calculate the compound interest on a principal of
1000 at a 5% interest rate over 10 periods.
Creating UDFs can significantly extend the capabilities of Excel, allowing you to perform custom calculations tailored to your
specific needs.
Excel VBA Intermediate
Message Boxes and Input Boxes
Let’s go through some examples of how to create Message Boxes and Input Boxes in Excel VBA.
1. Displaying a Message
To display a simple message box, you can use the MsgBox function. Here’s an example:
Sub DisplayMessage()
MsgBox "Hello, this is a simple message box!"
End Sub
Sub YesNoMessageBox()
Dim response As VbMsgBoxResult
response = MsgBox("Do you want to continue?", vbYesNo, "Yes/No Example")
Sub GetUserInput()
Dim userInput As String
userInput = InputBox("Please enter your name:", "User Input")
These examples should help you get started with creating Message Boxes and Input Boxes in Excel VBA.
Handling Errors
let’s look at handling errors in Excel VBA with some examples!
On Error GoTo 0: This is the default setting. It stops code execution and displays an error message.
On Error Resume Next: This tells VBA to ignore the error and continue with the next line of code.
On Error GoTo [label]: This directs VBA to jump to a specific line label when an error occurs.
Excel VBA Intermediate
Example:
Sub ExampleOnError()
On Error GoTo ErrorHandler
Dim x As Integer
x = 1 / 0 ' This will cause a division by zero error
Exit Sub
ErrorHandler:
MsgBox "An error occurred: " & Err.Description
End Sub
1. Drawing UserForms
To create a UserForm:
Open the Visual Basic for Applications (VBA) editor by pressing Alt + F11.
Insert a new UserForm by selecting Insert > UserForm.
Name: MyUserForm
Caption: Custom Dialog
To handle events like initializing the form, you can use the code window:
3. Using Text Boxes, Command Buttons, Combo Boxes, and Other Controls
You can add controls by selecting them from the Toolbox and drawing them
on the UserForm.
For example:
4. Formatting Controls
You can format controls by setting their properties. For example, to set the
text box properties:
Sub ShowMyUserForm()
MyUserForm.Show
End Sub
Excel VBA Intermediate
Example 1 Example 2
Here’s a complete example that ties everything together: Let’s create a more advanced UserForm example that includes
multiple controls, validation, and dynamic updates.
Create a UserForm named MyUserForm. We’ll create a form for user registration with fields for name,
Add a TextBox (TextBox1) and a CommandButton email, and age, and a submit button that validates the input
(CommandButton1). and displays a summary.
Set the properties and write the following code:
Private Sub UserForm_Initialize() Step-by-Step Advanced Example
Me.Caption = "Welcome to My Custom Dialog"
Me.TextBox1.Text = "Enter your name" 1. Drawing the UserForm
Me.TextBox1.Font.Size = 12 Open the VBA editor (Alt + F11).
Me.TextBox1.Font.Bold = True Insert a new UserForm (Insert > UserForm).
End Sub Name the UserForm UserFormRegistration.
.
Excel VBA Intermediate
' Validate Email ' Validate Email
If userEmail = "" Or InStr(1, userEmail, "@") = 0 Then If userEmail = "" Or InStr(1, userEmail, "@") = 0 Then
MsgBox "Please enter a valid email address.", vbExclamation MsgBox "Please enter a valid email address.", vbExclamation
Exit Sub Exit Sub
End If End If
UserForm Code: