Declaration of Variables, procedure arguments and Constants

declare variable in code vba

This page shows how you can save time by using Code VBA to declare new and insert existing variables and declare constants. For declaring variables, constants (and properties, functions and sub procedures) you can use the Code VBA menu or toolbar or the Code Builders pane.

Declaring Variables and procedure arguments using the Variable Builder

Toolbar: Declare Variable

When writing VBA code you will use quite a lot variables. Code VBA makes the insertion of VBA variables super fast and easy. Selecting the Byte item in the menu will insert Dim byt As Byte with the cursor after 'byt' so you can give a meaningful name.


You can also add a variable using the Variable Builder - a bit lower on the menu click this start demo showing insertion of variable to see it the builder in action. code vba declare variable demo

As demonstrated, you can use declare variable for

The prefix inserted at the location where you will name the variable follows the VBA naming conventions which is considered good practice. A benefit of following the prefix conventions is that it allows you to use variables without having to type the complete name by using the VDE intellisense feature. To get intellisense popup, type the prefix and next Ctl-[space]. Click this Start demo screencast to see how intellisense displays variables in your code that have the prefix you typed. Name file string selection demo

The Variable Builder toolbar button Variable Builder automatically adds the type prefix characters to the Name, so you don't have to do that. The types list box only shows the common VBA types and the most important ones available in the Office application you are working in. If the type you need is not listed, you can simply type it in the Type text box yourself - instead of selecting it using the list box.

Inserting existing variables

Inserting existing variables
Toolbar: Insert Variable

After declaring a variable you will want to use it in the code. The Variable Inserter on the toolbar shows which variables are locally available and lets you insert the name without having to type it.

An alternative approach to inserting existing variables is to use IntelliSense after typing the type prefix characters.

Adding arguments to a procedure

Another use for the variable builder is for inserting arguments for procedures:

  1. Put the cursor in the position in the procedure header where you want to add an argument
  2. Start the variable builder and give Name and select Type, press Insert

Declaring Constants using Code VBA

Toolbar: Declare Constant

In a similar way to the Variable Builder above constants may be added using the Constant Builder toolbar button Constant Builder. Constants are often used for filepaths and object names, so a logical next step is to insert the constant value using the Name insertion feature