Variables

Module 3 of 9

REMINDER: To fully understand Variables, you should have already watched the Variables Video in Canvas and followed along with the Macro Demo file. This practice will build upon that foundation.

Working with Variables in VBA

A variable is a named storage location in your computer's memory. Instead of hardcoding a value like a group number or GPR directly into your code, you store it in a variable and reference the variable name instead. This makes your macro adaptable — change the value once and it updates everywhere the variable is used.

Working with variables always follows three steps. Professor Sanders calls them Define, Populate, and Use — and that order is not optional. You must define a variable before you can populate it, and populate it before you can use it. If a value is wrong or blank, the first thing to check is whether these three steps are happening in the right order.

Variables show up in every exam question in some form. Getting the three steps and data types locked in now means one less thing to think about on exam day.

The Three Steps

Defining a variable creates a named slot in memory and tells VBA what kind of data it will hold. Populating it places a value in that slot. Using it means referencing the variable name anywhere you need that value — in a cell assignment, a MsgBox, or a loop condition.

Syntax

' Step 1 — DEFINE
Dim VariableName As DataType

' Step 2 — POPULATE
VariableName = something

' Step 3 — USE
ActiveCell = VariableName

Here is the three-step pattern in a real macro — prompting for a group number and writing it to a cell:

Dim NewGroup As Integer

NewGroup = InputBox("Enter the new group number")

Selection.End(xlDown).Select
ActiveCell.Offset(1, 0).Select
ActiveCell = NewGroup

Data Types

The data type tells VBA how to store the value in memory. Using the wrong type causes silent errors — an Integer silently truncates a decimal, a String won't compare correctly to a number. For this course you need five types: String for text, Integer for small whole numbers, Long for large whole numbers like student IDs, Double for numbers with decimal places like GPR, and Date for dates.

Syntax

Dim LastName    As String    ' text
Dim GroupNumber As Integer   ' whole number up to ~32,000
Dim StudentID   As Long      ' whole number any size
Dim GPR         As Double    ' number with decimals
Dim StartDate   As Date      ' date value

These are the actual variable declarations from the Project Demo:

Dim NewGroup       As Integer   ' group number — small whole number
Dim NumberAccepted As Integer   ' counter — small whole number
Dim UIN            As Long      ' 9-digit student ID — needs Long
Dim GPR            As Double    ' GPA with decimals
Dim Gender         As String    ' text
Dim Birthdate      As Date      ' date

Option Explicit

By default, VBA lets you use any word as a variable without declaring it. This causes three problems: VBA may choose the wrong data type, a misspelled variable name silently creates a new blank variable instead of an error, and your macro runs slower. Adding Option Explicit at the very top of the module — above the first Sub — forces you to declare every variable. If you use an undeclared name, VBA stops and tells you exactly where the problem is.

Syntax

Option Explicit          ' ← must be the very first line in the module

Sub YourMacroName()
    Dim VariableName As DataType
End Sub

This is what the top of every well-written module looks like:

Option Explicit
' ACCT 628 - Sanders

Sub Option1_Modified()

    Dim NewGroup       As Integer
    Dim NumberAccepted As Integer
    Dim UIN            As Long
    Dim GPR            As Double
    Dim Gender         As String
    Dim Birthdate      As Date

End Sub

Variables vs Named Ranges

Variables and Named Ranges look similar but behave very differently. A variable exists only while the macro is running — when the macro stops, it's gone. A Named Range exists on the worksheet permanently and can be used in both Excel formulas and VBA. In VBA, Named Ranges always use quotes: Range("GroupData"). Variables never use quotes.

Syntax

            ' Variable — no quotes, exists only while macro runs
              LegalDrinkingAge = InputBox("Enter the current legal drinking age")

            ' Named Range — quotes required, exists on worksheet
              Range("LegalDrinkingAge") = LegalDrinkingAge

This example from the Macro Handout shows both in the same macro:

Dim LegalDrinkingAge As Integer

LegalDrinkingAge = InputBox("Enter the current legal drinking age")

' Named Range has quotes — Variable does not
Range("LegalDrinkingAge") = LegalDrinkingAge

Quick Check

1. What are the three steps for working with variables? Use Professor Sanders' exact terms.

2. A student's UIN is a 9-digit number like 123456789. Which data type should you use?

3. You declare Dim GPR As Integer and assign it 3.756. What value does GPR contain?

4. Where must Option Explicit be placed?

5. In VBA, how do you reference a Named Range called "GroupData"?

Question 3 is the classic trap. Integer looks right until you assign a decimal and it silently rounds. Always ask: could this value have a decimal? If yes, use Double.

Easy Wins

Your First Variable Guided

Write a macro that asks for a name using InputBox, stores it in a String variable, and displays "Hello, [name]!" in a MsgBox.

Open the VBA Editor (Alt+F11). Insert a module (Insert → Module). Type this shell to start:

Option Explicit
Sub SayHello()

End Sub
Data Type Experiment Observation

Copy this code into the VBA Editor and run it. Look at what Integer does to 3.7 vs what Double does. What's different and why?

Dim WholeNumber   As Integer
Dim DecimalNumber As Double

WholeNumber   = 3.7
DecimalNumber = 3.7

MsgBox "Integer: " & WholeNumber & " | Double: " & DecimalNumber

Three Steps in Order Guided

Write a macro that reads a student's ID, last name, and GPR from cells A2, B2, and D2, stores them in variables, then displays all three in a MsgBox.

Open the VBA Editor and create this shell with your three variable declarations. Notice the data types: Long for the ID, String for the name, Double for GPR.

Option Explicit
Sub ReadStudent()
    Dim StudentID As Long
    Dim LastName  As String
    Dim GPR       As Double

Sample Data

Copy this data and paste it into cell A1 of a new Excel worksheet. Use Ctrl+V to paste — Excel will automatically split the columns. This is your practice dataset for the exercises below.

Practice Problem

Read the First Applicant

Using the Aggie Advisors data you just pasted into Excel, write a macro that reads the first applicant record and displays their information in a MsgBox.

What your macro needs to do:

  • Declare four variables with correct data types: StudentID (Long), LastName (String), FirstName (String), GPR (Double)
  • Navigate to cell A2 (row 1 is the header)
  • Populate each variable using Offset: StudentID = ActiveCell (column A), LastName = Offset(0, 1) (column B), FirstName = Offset(0, 2) (column C), GPR = Offset(0, 3) (column D)
  • Display: "ID: [X] | Name: [Last], [First] | GPR: [X.XXX]"

Expected result for row 2: "ID: 724816395 | Name: Anderson, Emma | GPR: 3.842"

Hint:

MsgBox "ID: " & StudentID & " | Name: " & LastName & ", " & FirstName & " | GPR: " & GPR
See this in the Aggie Advisors project →

Challenge

These exercises are perfect preparation for the Sample Exam, which prepares you for the Macro Project Exam itself. Exam format may vary by semester.

Read and Display the First Applicant

No hints. No steps. This is exam level.

Using the Aggie Advisors dataset, write a macro that demonstrates all three steps of working with variables — Define, Populate, and Use. Your macro must:

  • Use Option Explicit at the top of the module
  • Declare four variables with the correct data types: StudentID as Long, LastName as String, FirstName as String, GPR as Double
  • Navigate to cell A2 on your Applicant Information sheet
  • Populate each variable from the correct column using Offset: StudentID from column A (ActiveCell), LastName from column B (Offset 0,1), FirstName from column C (Offset 0,2), GPR from column D (Offset 0,3)
  • Display all four in a single MsgBox formatted exactly as:
    ID: [StudentID] | Name: [LastName], [FirstName] | GPR: [GPR]

No loops. No IF statements. Variables only — this is a Module 3 challenge.

Expected result: ID: 724816395 | Name: Anderson, Emma | GPR: 3.842

See this in the Aggie Advisors project →