3.1 What are Variables?
A variable is a temporary storage location used in VBA to store values during program execution. It allows your program to remember data and use it later.
Example: If you want to store a student's name, marks, or product price, you must use variables.
3.2 Why Do We Use Variables?
- To store data temporarily.
- To use the same value multiple times.
- To make programs dynamic and flexible.
- To perform calculations.
- To improve readability and structure.
3.3 Syntax for Declaring Variables
Examples:
3.4 Rules for Naming Variables
- Must start with a letter.
- No spaces allowed (use underscore instead).
- No special characters like @, #, %, etc.
- Avoid VBA keywords (If, Loop, Dim etc.).
- Use meaningful names (marks, totalSalary, studentName).
3.5 Variable Scope (Very Important)
Scope means where the variable can be accessed.
- Local Variables – Declared inside a procedure. Accessible only there.
- Module-level Variables – Declared at top of module using Dim or Private.
- Global Variables – Declared using Public and accessible across all modules.
Example: Using Variables
Sub VariableExample()
Dim name As String
Dim age As Integer
Dim salary As Double
name = "Amit"
age = 25
salary = 45000.5
MsgBox "Name: " & name & vbCrLf & _
"Age: " & age & vbCrLf & _
"Salary: " & salary
End Sub
Dim name As String
Dim age As Integer
Dim salary As Double
name = "Amit"
age = 25
salary = 45000.5
MsgBox "Name: " & name & vbCrLf & _
"Age: " & age & vbCrLf & _
"Salary: " & salary
End Sub
Output:
Name: Amit
Age: 25
Salary: 45000.5

0 Comments