How To Declare Variables And Public Keywords With VBA In Excel
How to declare VBA variables?
A variable is simply used to store temporary information that is used in the execution of a process, procedure, workbook or a module.
There are a few rules you have to keep in mind when naming your variables:
- Variable name must start with a letter and not a number (number can be used but not as first letter in a variable name)
- Variable name must not be a keyword(predefined word)in Excel VBA
- Variable name must be <250 characters always
Now let’s see some of the types of variables
A variable can be of these types
- Integer (positive numbers and negative numbers)
- String (numbers, letters, special characters like @)
- Char (letters only)
Now let’s learn how to declare a variable. Follow the steps to declare a variable in Excel VBA.
Note: you can skip STEP-1 and STEP-2 if the developer tab is already open.
STEP-1
First you need to open the developer tab. To do this right click anywhere on the ribbon and select “Customize the Ribbon” from the drop down menu.
STEP-2
An option dialog box will open. Click on the DEVELOPER check box (it is under “Customize the Ribbon Main Tabs“) and press ok.
STEP-3
The Developer tab is now open and is present next to the view.
Click on the developer tab and select “View Code” from the ribbon.
STEP-4
A new window will open (Visual Basic Editor) which would have a dialogbox in the center.
You will declare the variable in this dialogbox
STEP-5
Now you can declare a variable. To declare a variable use the keyword “Dim” (short for dimension) followed by a variable name then the word “As” followed by a variable type. For example:
Dim myword As String
Note: dim is a keyword used to declare the variable. “myword” is the name of my variable. “String” is the type of my variable
IMPORTANT: ALL VARIABLES MUST BE DECLARED BETWEEN Private Sub and End Sub. OTHERWSE IT WILL NOT WORK
STEP-6
You can also declare a variable of type int. Like this:
Dim myword As Integer
STEP-7
You can also declare multiple variables. Like this:
Dim myword,myword2,myword3 as Integer
Note: “myword” is the name of my first variable, “myword2” is the name of my second variable and “myword3” is the name of the third variable. “String” is the type of all these variable.
STEP-8
You can also declare multiple variables of different types. Like this:
Dim myword As Integer Dim myword2 As String
STEP-9
(optional) You can use the “Public” keyword to declare public module-level variable.
Public myword As Integer
Note: you have replaced the keyword “Dim” with the keyword “Public”.
Public variables can be used in any of the Excel VBA procedure
Template
Further reading: Basic concepts Getting started with Excel Cell References