Variables are fundamental building blocks in Excel VBA programming. Think of them as labeled containers in your computer's memory that hold information which can change during program execution. Just like the files in your cabinet or mailboxes where content changes over time, variables store and manage data dynamically in your VBA programs.
Proper naming of variables is crucial for writing clean, maintainable code. Follow these rules and recommendations:
totalSales
instead of ts
)strName
for String, intCount
for IntegerSub
, End
, If
)Valid Names | Invalid Names | Reason |
---|---|---|
My_Car | My.Car | Period not allowed |
Year2023 | 2023Year | Starts with number |
Employee_Name | Employee Name | Contains space |
TotalAmount$ | Total$Amount | Dollar sign only at end |
Choosing the right data type is essential for efficient memory usage and preventing errors. VBA data types fall into two main categories:
Numeric types store numbers for mathematical operations. Select carefully based on your needs:
Data Type | Storage | Range | When to Use |
---|---|---|---|
Byte | 1 byte | 0 to 255 | Small positive numbers (e.g., age, ratings) |
Integer | 2 bytes | -32,768 to 32,767 | Whole numbers (e.g., loop counters) |
Long | 4 bytes | -2.1B to 2.1B | Large whole numbers (e.g., population) |
Single | 4 bytes | ±3.4E±38 | Floating-point (e.g., measurements) |
Double | 8 bytes | ±1.7E±308 | Precise calculations (e.g., scientific data) |
Currency | 8 bytes | ±922,337T | Financial calculations (fixed decimal) |
Decimal | 12 bytes | ±7.9E±28 | Extreme precision (e.g., accounting) |
These types handle text, dates, true/false values, and more:
Data Type | Storage | Range/Values | Example Usage |
---|---|---|---|
String (fixed) | Length | 1-65,400 chars | Dim ID As String * 10 '10-char ID |
String (variable) | Length + 10B | 0-2B chars | Dim name As String 'Variable name |
Date | 8 bytes | 1/1/100-12/31/9999 | Dim birthDate As Date |
Boolean | 2 bytes | True/False | Dim isComplete As Boolean |
Object | 4 bytes | Any object | Dim ws As Worksheet |
Variant | 16-22B | Any data | Dim anything 'Flexible but inefficient |
Use the VarType
function to check variable types at runtime. Here's an expanded example:
Sub TestDataTypes()
'Declare variables with different types
Dim studentName As String
Dim examScore As Integer
Dim tuitionFee As Currency
Dim enrollmentDate As Date
Dim isScholarship As Boolean
'Assign values
studentName = "Sarah Johnson"
examScore = 92
tuitionFee = 1250.75
enrollmentDate = #9/1/2023#
isScholarship = True
'Test types and display results
MsgBox "Name type: " & VarType(studentName) & vbCrLf & _
"Score type: " & VarType(examScore) & vbCrLf & _
"Fee type: " & VarType(tuitionFee) & vbCrLf & _
"Date type: " & VarType(enrollmentDate) & vbCrLf & _
"Boolean type: " & VarType(isScholarship)
End Sub
The VarType
function returns numeric codes representing data types. Common return values include:
Proper variable declaration improves code reliability and performance.
Implicit Declaration (not recommended):
'VBA creates a Variant automatically
customerCount = 25
Explicit Declaration (recommended):
'Clear and specific
Dim customerCount As Integer
customerCount = 25
Multiple Declarations:
'Compact but less readable
Dim x As Integer, y As Double, name As String
'Better - one per line
Dim rowCount As Integer
Dim columnCount As Integer
Dim sheetName As String
Fixed-Length Strings:
'For database compatibility
Dim employeeID As String * 6 'Always 6 characters
employeeID = "A12345" 'Works
employeeID = "A1234567" 'Truncated to "A12345"
Variables have different lifetimes and visibility depending on where and how they're declared:
Keyword | Scope | Lifetime | Example |
---|---|---|---|
Dim | Procedure-level | Procedure execution | Sub Calculate() Dim total As Double End Sub |
Private | Module-level | Application run | Private mCount As Integer |
Static | Procedure-level | Application run | Sub TrackCalls() Static callCount As Integer End Sub |
Public | Global | Application run | Public gUserName As String |
Constants store values that shouldn't change during program execution. They make code more readable and maintainable.
'Basic syntax
Const CONSTANT_NAME As DataType = Value
'Practical examples
Const PI As Double = 3.14159265358979
Const MAX_USERS As Integer = 100
Const COMPANY_NAME As String = "Acme Corp"
Const TAX_RATE As Single = 0.075
By convention, constants are named in ALL_CAPS with underscores for readability:
Const DISCOUNT_RATE As Double = 0.15
Const FILE_PATH As String = "C:\Reports\"
VBA provides many useful predefined constants:
'Color constants
Range("A1").Interior.Color = vbRed
'Date constants
If currentDate > vbMonday Then
'MessageBox constants
MsgBox "Continue?", vbYesNo + vbQuestion
Sub CalculateGrade()
'Declare constants
Const PASS_MARK As Integer = 50
Const MAX_SCORE As Integer = 100
'Declare variables
Dim studentName As String
Dim testScore As Integer
Dim isPassing As Boolean
'Assign values
studentName = "John Smith"
testScore = 78
isPassing = (testScore >= PASS_MARK)
'Display results
MsgBox "Student: " & studentName & vbCrLf & _
"Score: " & testScore & "/" & MAX_SCORE & vbCrLf & _
"Status: " & IIf(isPassing, "Pass", "Fail")
End Sub
Sub ConvertTemperature()
'Declare conversion constants
Const FAHRENHEIT_FREEZING As Single = 32
Const CONVERSION_FACTOR As Single = 5 / 9
'Declare variables
Dim fahrenheit As Single
Dim celsius As Single
'Get input
fahrenheit = InputBox("Enter temperature in Fahrenheit:")
'Calculate conversion
celsius = (fahrenheit - FAHRENHEIT_FREEZING) * CONVERSION_FACTOR
'Display result
MsgBox fahrenheit & "°F = " & Round(celsius, 1) & "°C"
End Sub
Option Explicit
Copyright ® 2020 Dr.Liew Voon Kiong . All rights reserved [Privacy Policy]
Contact: Facebook Page