vba dim
vba dim
DataType: The type of data the variable will hold (e.g., Integer, String, Double,
etc.).
myNumber = 10
myText = "Hello, World!"
myPrice = 5.99
vba
Copy
Dim num As Integer
Long: Similar to Integer but can hold larger numbers.
vba
Copy
Dim largeNum As Long
Double: Used for numbers with decimals (e.g., 3.14, 2.5).
vba
Copy
Dim price As Double
String: Used to store text.
vba
Copy
Dim name As String
Boolean: Used to store True or False values.
vba
Copy
Dim isActive As Boolean
Variant: A special type that can hold any kind of data (used when you're unsure
about the data type).
vba
Copy
Dim anyData As Variant
Object: Used for objects, such as Excel ranges, worksheets, or other objects.
vba
Copy
Dim ws As Worksheet
Example with Different Data Types:
vba
Copy
Sub MultipleDimExample()
Dim name As String ' Text data
Dim age As Integer ' Integer number
Dim height As Double ' Decimal number
Dim isStudent As Boolean ' Boolean value
name = "John"
age = 25
height = 5.9
isStudent = True
Variable Scope: By default, variables declared with Dim are local to the procedure
in which they're declared. If you want a variable to be accessible across different
procedures, you would declare it at the module level with Private or Public.
Option Explicit: It's a good practice to use Option Explicit at the top of your
modules. It forces you to declare all variables, preventing errors from using
undeclared variables.
vba
Copy
Sub LocalScopeExample()
Dim localVar As Integer ' Only accessible inside this subroutine
localVar = 10
End Sub
Module-Level Scope (using Private or Public): The variable is accessible to all
procedures within the module (or across all modules if Public is used).
vba
Copy
Private moduleVar As Integer ' Accessible to all procedures in the same module
Public globalVar As String ' Accessible to all modules in the workbook