Chapter 3: Variables in VBA – The Memory Power of Your Code

  Variables in VBA – Explained for Beginners”

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.

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

Output:
Name: Amit
Age: 25
Salary: 45000.5


Post a Comment

0 Comments