Chapter 2 – Data types and Variables
In this chapter, we will learn different data types used in VBA, their usage and practical examples of declaring variables. Finally we will learn valid variable names and Naming Conventions.
Data Types
Data Type | Used For |
Integer | To store whole numbers from -32768 to 32767 |
Long | To store whole numbers from -2147483648 to 2147483648 |
String | To store alphanumeric data |
Date | To store date and time |
Double | To store decimal values |
Boolean | To store True or False |
Variant | To store any time of data |
Object | To store objects |
How to Declare Variables
VBA provides very simple way to declare variables, using Dim statement you can declare variables
Syntax:
Dim VariableName as DataType
Example 1:
Code:
Dim strName As String
Result: VBA creates a variable named strName with String data type
Example 2:
Code:
Dim iNumber As Integer
Result: VBA creates a variable named iNumber with Integer data type
Example 3:
Code:
Dim objOutlook As Object
Result: VBA creates a variable named objOutlook with Object data type
Example 4:
Code:
Dim vResult
Result: VBA creates a variable named vResult with Variant data type
Valid Variable Names
- Variable name must begin with a letter
- Variable name cannot be more than 255 character long
- Variable names cannot contain space and periods, you can use underscore (_) in place of space and periods
- Variables in VBA are non-case sensitive that means you cannot declare two variables with names strName and strNAME
Naming Conventions
Most of the developers follow a naming convention while declaring the variables. You can also call it as prefix which is used in the beginning of a variable name. A good naming convention helps you and others to easily read and understand the codes. See below the list of commonly used naming conventions:
Data Type | Naming Convention (Prefix) | Example |
Integer | I | iNumber |
Long | L | lCounter |
String | Str | strName |
Date | Dte | dteDOB |
Double | Dbl | dblAmount |
Boolean | B | bIsFound |
Variant | V | vResult |
Object | Obj | objApplication |