Setting variables in excel vba

Excel VBA Tutorial about defining and declaring variablesOne of the main objectives of VBA and (more generally) Excel is to work with (and manipulate) data.

This data is generally stored in the computer’s memory. For purposes of this Excel guide, we’ll distinguish between the following 2 places to store data:

  • Objects.
  • Variables.

The former topic (objects) is covered in other Excel tutorials within Power Spreadsheets, including here and here. This blog post focuses on the latter topic (VBA variables).

Variables are often used when working with Visual Basic for Applications.

You have a substantial degree of flexibility when declaring VBA variables. This flexibility in declaring VBA variables can lead to poor coding practices. Poor coding practices can lead to potential problems down the road. These problems can lead to big headaches.

My purpose with this Excel tutorial is to help you avoid those headaches. Therefore, in this blog post, I explain the most important aspects surrounding VBA variable declaration. More specifically, this guide is divided in the following sections:

Let’s start by taking a detailed look at…

What Is A VBA Variable

For purposes of this blog post, is enough to remember that a variable is, broadly, a storage location paired with a name and used to represent a particular value.

As a consequence of this, variables are a great way of storing and manipulating data.

This definition can be further extended by referencing 3 characteristics of variables. A VBA variable:

  1. Is a storage location within the computer’s memory.
  2. Is used by a program.
  3. Has a name.

In turn, these 3 main characteristics of variables provide a good idea of what you need to understand in order to be able to declare variables appropriately in VBA:

  1. How do you determine the way in which the data is stored, and how do you actually store the data. These items relate to the topics of data types (which I cover in a separate post) and VBA variable declaration (which I explain below).
  2. How do you determine which program, or part of a program, can use a variable. This refers to the topics of variable scope and life.
  3. How do you name VBA variables.

I explain each of these 3 aspects below.

This Excel tutorial doesn’t cover the topic of object variables. This is a different type of VBA variable, which serves as a substitute for an object. I may, however, cover that particular topic in a future blog post.

Since this how-to guide focuses on declaring variables in VBA, and we’ve already seen what a variable is, let’s take a look at…

Why Should You Declare Variables Explicitly In VBA

Before I explain some of the most common reasons to support the idea that you should declare your VBA variables explicitly when working with Visual Basic for Applications, let’s start by understanding what we’re actually doing when declaring a variable explicitly. At a basic level: When you declare a variable, the computer reserves memory for later use.

Now, the common advice regarding VBA variable declaration says that declaring variables is an excellent habit.

There are a few reasons for this, but the strongest has to do with Excel VBA data types. The following are the main points that explain why, from these perspective, you should get used to declaring variables when working in Visual Basic for Applications:

  • VBA data types determine the way in which data is stored in the computer’s memory.
  • You can determine the data type of a particular VBA variable when declaring it. However, you can also get away with not declaring it and allowing Visual Basic for Applications to handle the details.
  • If you don’t declare the data type for a VBA variable, Visual Basic for Applications uses Variant (the default data type).
  • Despite being more flexible than other data types, and quite powerful/useful in certain circumstances, relying always on Variant has some downsides. Some of these potential problems include inefficient memory use and slower execution of VBA applications.

When you declare variables in VBA, you tell Visual Basic for Applications what is the data type of the variable. You’re no longer relying on Variant all the time. Explicitly declaring variables and data types may result in (slightly) more efficient and faster macros.

Even though the above is probably the main reason why you should always declare variables in Visual Basic for Applications, it isn’t the only one. Let’s take a look at other reasons why you should declare variables when working with Visual Basic for Applications:

Additional Reason #1: Declaring Variables Allows You To Use The AutoComplete Feature

Let’s take a look at the following piece of VBA code.

Section of VBA code before declaring variable

You can see the whole VBA code of the Variable_Test macro further below.

This Excel VBA Variables Tutorial is accompanied by Excel workbooks containing the data and macros I use. You can get immediate free access to these example workbooks by subscribing to the Power Spreadsheets Newsletter.

The next statements in the macro (after those that appear above) are:

MsgBox “the value of Variable One is ” & Variable_One & _

Chr(13) & “the value of Variable Two is ” & Variable_Two

Let’s imagine that you’re typing these statements and are currently at the following point:

Beginning of typing shortcut for declared variables

Theoretically, you must type the whole name of the variable: “Variable_One”. However, declaring the VBA variable previously allows you to take advantage of a keyboard shortcut: “Ctrl + Space”. Once you’ve typed the first few (can be as little as 2 or 3) letters of a declared variable name, you can press “Ctrl + Space” and the Visual Basic Editor does one of the following:

  • As a general rule, the VBE completes the entry.
  • If there is more than 1 option available, the Visual Basic Editor displays a list of possible matches to complete the entry.

In the case above, using the “Ctrl + Space” shortcut results in the Visual Basic Editor displaying a list of possible matches to complete the entry. This is shown in the following image.

List of options with keyboard shortcut for declared variable

Notice how the list above, in addition to Variable_One and Variable_Two, also includes other reserved words and functions.

This is because the same keyboard shortcut (“Ctrl + Space”) also works for those 2 other elements. However, those are topics for future blog posts.

Now, let’s assume that you pressed the “Ctrl + Space” keyboard shortcut at the following point:

VBA code before variable typing keyboard shortcut

In this case, the Visual Basic Editor completes the entry.

Keyboard shortcut to type declared variable

Additional Reason #2: Declaring Variables Makes VBA Carry Out Additional Error Checking

Some errors in Visual Basic for Applications may be very difficult to spot, particularly in large or complex VBA applications.

By declaring your VBA variables and defining their data type, you get some additional help from Visual Basic for Applications. When you explicitly declare the data type of your variables, VBA carries out some additional checking when compiling the code. In some of these cases, VBA can identify certain errors while you’re working on the code.

The most common type of error that VBA can catch this way is data-typing errors. These errors are caused by incorrectly assigning certain information to a particular variable. More precisely, this usually happens when the assignment results in a mismatch between the following:

  • The data type of the variable; and
  • The type of the data assigned to the variable.

The following are some examples of how this can occur:

  • You declare an Integer or Byte variable, but try to assign a string to it. The Integer and Byte data types are designed to store certain integers, not strings.
  • You declare a Boolean variable, but try to assign a large integer to it. Variables of the Boolean data type can only be set to the 2 Boolean values (TRUE and FALSE).

Appropriately declaring your VBA variables (usually) allows you to notice these kind of mistakes as soon as possible after the variable has received an unexpected data type.

Additional Reason #3: Declaring Variables Improves Code Readability, Makes Debugging Easier And Reduces The Risk Of Certain Mistakes

As I explain below, whenever you declare VBA variables explicitly, you generally place all the variable declarations at the beginning of a module or procedure. This improves the readability of your VBA code.

Additionally, declaring variables explicitly makes your VBA code easier to debug and edit.

Finally, getting used to always declaring variables explicitly by following the different suggestions that appear in this Excel tutorial reduces the risk of certain mistakes. Among others, explicitly declaring variables reduces the risk of both:

  • Variable naming-conflict errors; and
  • Spelling or typographical mistakes.

Naming-conflict errors are quite dangerous. If you don’t declare VBA variables, there is a higher risk of accidentally over-writing or wiping out a pre-existing variable when trying to create a new one.

Spelling mistakes can also create big problems. I explain one of the main ways in which taking measures to declare variables always helps you reduce spelling mistakes below.

However, in addition to that particular way, variable declaration also helps reduce spelling mistakes by capitalizing all the lower-case letters (in a variable name) that were capitalized at the point of the declaration statement.

To see how this works, let’s go back to the VBA code for the Variable_Test macro. Let’s assume that you type the name of Variable_One without capitalizing (as shown below):

Declared variable name in VBA

Once you complete the statement, the Visual Basic Editor automatically capitalizes the appropriate letters. This looks as follows:

VBA variable with capitalized name

You can, for example, make it a habit to (i) use some capital letters in your VBA variable names but (ii) type the body of your VBA code in only lowercase letters. If the Visual Basic Editor doesn’t capitalize a variable name after you’ve typed it, you may have typed the name wrongly. The VBE (generally) does this automatic capitalization for all keywords (not only VBA variables).

All of the advantages that I list under Additional Reason #3 are, in the end, related to the fact that variable declaration helps you (and VBA itself) have a better idea of what variables exist at any particular time.

So I suggest you save yourself some potential problems by getting used to declaring your VBA variables explicitly.

The Disadvantage Of Declaring VBA Variables Explicitly

Despite the advantages described above, the idea that you should always declare VBA variables explicitly is not absolutely accepted without reservations.

Most VBA users agree that declaring variables explicitly is (usually) a good idea.

However, some VBA users argue that both approaches have advantages and disadvantages. From this perspective, the main disadvantage of explicit variable declaration is the fact that it requires some upfront time and effort. In most cases, these disadvantages are (usually) outweighed by the advantages of explicit variable declaration.

In practice, however, it seems that for several VBA programmers the fact that declaring variables require slightly more time and effort isn’t outweighed by the advantages described above. In fact, some developers do not declare variables explicitly.

I provide a general explanation of how to create a VBA variable without declaring it (known as declaring a variable implicitly) below.

However, let’s assume for the moment that you’re convinced about the benefits of declaring VBA variables. You want to do it always: no more undeclared variables.

In order to ensure that you follow through, you may want to know…

How To Remember To Declare Variables

Visual Basic for Applications has a particular statement that forces you to declare any variables you use. It’s called the Option Explicit statement.

Whenever the Option Explicit statement is found within a module, you’re prevented from executing VBA code containing undeclared variables.

The Option Explicit statement just needs to be used once per module. In other words:

  • You only include 1 Option Explicit statement per module.
  • If you’re working on a particular VBA project that contains more than 1 module, you must have 1 Option Explicit statement in each module.

Including the Option Explicit statement in a module is quite simple:

Just type “Option Explicit” at the beginning of the relevant module, and before declaring any procedures. The following image shows how this looks like:

Force variable declaration with Option Explicit statement

Once you’ve included the Option Explicit statement in a module, Visual Basic for Applications doesn’t execute a procedure inside that module unless absolutely all the variables within that procedure are declared. If you try to call such procedure, Excel displays the following compile-time error message:

Error message for undeclared variable

In addition to the reasons I provide above to support the idea that you should declare your VBA variables, there is an additional advantage when using the Option Explicit statement and having to declare absolutely all of your variables:

The Visual Basic Editor automatically proofreads the spelling of your VBA variable names.

Let’s see exactly what I mean by taking a look at a practical example:

Let’s go back to the Variable_Test macro that I introduced above. The following screenshot shows the full Sub procedure:

Macro example for declaring a VBA variable

Notice how, at the beginning of the Sub procedure, the variables Variable_One and Variable_Two are declared. I explain how to declare VBA variables below.

Declared variables in VBA code example

Notice, furthermore, how each of these variables appears 2 times after being declared:

Declared VBA variable

Let’s assume that while writing the VBA code, you made a typo when writing the name of the VBA variable Variable_One (you typed “Variable_Ome”). In such a case, the code of the Variable_Test macro looks as follows:

Typo in declared VBA variable name

Such small typos can be difficult to spot in certain situations. This is the case, for example, if they’re present within the VBA code of a large Sub procedure or Function procedure where you’re working with several different variables. This may be a big problem…

If you fail to notice these kind of typos within in the names of variables, Excel interprets the different spellings as different variables (for example, Variable_One and Variable_Ome). In other words, Excel creates a new variable using the misspelled name. This leads to having several variables even though you think you only have one and, in certain cases, may end in the macro returning the wrong result.

However, when you misspell the name of a VBA variable while having the Option Explicit statement enabled, Excel warns you about it. The following image shows the error message that is displayed when I try to run the Variable_Test macro with the typo shown above. Notice how the Visual Basic Editor:

  • Clearly informs you that there is an undefined variable.
  • Highlights the element of the VBA code where the mistake is.

Undefined variable error in VBA

Using the Option explicit statement is (generally) suggested.

Therefore, let’s take this a step further by seeing how to ensure that the Option Explicit statement is always enabled:

How To Remember To Declare Variables Always

The Option Explicit statement is not enabled by default. This means that, if you want to use it always, you’d have to enable it for every single module you create.

However, the Visual Basic Editor is highly customizable. One of the customizations you can make is have the VBE always require that you declare your variables. The Visual Basic Editor does this by automatically inserting the Option Explicit statement at the beginning of any VBA module.

Enabling this option is generally recommended. If you want to have the Visual Basic Editor insert the Option Explicit statement in all your future modules, follow these 2 easy steps:

Step #1: Open The Options Dialog

You can get to the Options dialog of the Visual Basic Editor by clicking on the Tools menu and selecting “Options…”.

First step to enable Option Explicit statement by default

Step #2: Enable “Require Variable Declaration” And Click On The OK Button

The Visual Basic Editor should display the Editor tab of the Options dialog by default. Otherwise, simply click on the relevant tab at the top of the dialog.

Within the Editor tab, you simply need to enable “Require Variable Declaration” by ticking the box next to it. Then, click the OK button at the lower right corner of the dialog to complete the operation.

Enabling Require Variable Declaration in VBE

Note that enabling Require Variable Declaration option only applies to modules created in the future. In other words, Require Variable Declaration doesn’t insert the Option Explicit statement in previously existing modules that were created while the option wasn’t enabled.

You can learn more about customizing the Visual Basic Editor through the Options dialog, including a detailed description of the Require Variable Declaration setting, by clicking here.

You already know how to determine the way in which data is stored by using VBA data types. Let’s take a look at how you actually store the data or, in other words…

How To Declare A Variable In VBA

The most common way of declaring a variable explicitly is by using the Dim statement. In practice, you’re likely to use Dim for most of your variable declarations.

You’ve already seen this type of statement within the Variable_Test macro shown above. In that particular case, the Dim statement is used to declare the Variable_One and Variable_Two variables as follows:

Declare VBA variable with Dim statement

Both variables are being declared as being of the Integer data type.

3 other keywords (in addition to Dim) may be used to declare a VBA variable explicitly:

  1. Static.
  2. Public.
  3. Private.

As explained below, you generally use these 3 latter statements to declare variables with special characteristics regarding their scope or lifetime.

Regardless of the keyword that you’re using to declare a variable, the basic structure of the declaration statement is the same:

Keyword Variable_Name As Data_Type

In this structure:

  • “Keyword” is any of the above keywords: Dim, Static, Public or Private. In the following sections, I explain when is appropriate to use each of these.
  • “Variable_Name” is the name you want to assign to the variable. I explain how to name VBA variables below.
  • “Data_Type” makes reference to the data type of the variable. This element is optional, but recommended.

The question of which is the exact keyword that you should use to declare a particular VBA variable depends, mostly, on the scope and life you want that particular variable to have.

The following table shows the relationship between the 4 different statements you can use to declare a VBA variable and the 3 different scopes a variable can have:

Variable Scope Possible Keywords Location Of Variable Declaration Statement
Procedure-only Dim or Static Within procedure
Module-only Dim or Private Within module, but before any procedure
Public Public Within module, but before any procedure

I introduce the Dim, Static, Private and Public statements in the following sections. However, as you read their descriptions, you may want to constantly refer to the section below which covers VBA variable scope.

How To Declare A VBA Variable Using The Dim Statement

The Dim statement is the most common way to declare a VBA variable whose scope is procedure-level or module-level. I cover the topic of variable scope below.

Dim stands for dimension. In older versions of BASIC, this (Dim) statement was used to declare an array’s dimensions.

Nowadays, in VBA, you use the Dim keyword to declare any variable, regardless of whether it is an array or not.

The image above shows the most basic way in which you can use the Dim statement to declare VBA variables. However, you can also use a single Dim statement to declare several variables. In such cases, you use a comma to separate the different variables.

The following screenshot shows how you can declare Variable_One and Variable_Two (used in the sample Variable_Test macro) by using a single Dim statement:

How to declare several VBA variables with single Dim statement

Even though this structure allows you to write fewer lines of VBA code, it (usually) makes the code less readable.

Regardless of whether you declare VBA variables in separate lines or in a single line, note that you can’t declare several variables to be of a determined data type by simply separating the variables with a comma before declaring one data type. As explained in Excel 2013 Power Programming with VBA:

Unlike some languages, VBA doesn’t let you declare a group of variables to be a particular data type by separating the variables with commas.

In other words, the following statement is not the equivalent as that which appears above:

Declaring several variables with single data type mistake

In this latter case, only Variable_Two is being declared as an Integer.

In the case of Variable_One, this piece of code doesn’t declare the VBA data type. Therefore, Visual Basic for Applications uses the default type: Variant.

The location of the Dim statement within a VBA module depends on the desired variable scope. I explain the topic of variable scope, and where to place your Dim statements depending on your plans, below.

How To Declare A Variable Using The Static Statement

You can use the Static statement to declare procedure-level VBA variables. It’s an alternative to the Dim statement.

I explain the topic of variable scope below. However, for the moment, is enough to understand that procedure-level VBA variables can only be used within the procedure in which they are declared.

The main difference between VBA variables declared using the Dim statement and variables declared using the Static statement is the moment in which the variable is reset. Let’s take a look at what this means precisely:

As a general rule (when declared with the Dim statement), all procedure-level variables are reset when the relevant procedure ends. Static variables aren’t reset; they retain the values between calls of the procedure.

Static VBA variables are, however, reset when you close the Excel workbook in which they’re stored. They’re also reset (as I explain below) when a procedure is terminated by an End statement.

Despite the fact that Static variables retain their values after a procedure ends, this doesn’t mean that their scope changes. Static variables continue to be procedure-level variables and, as such, they´re only available within the procedure in which they’re declared.

These particular characteristics of Static variables make them particularly useful for purposes of storing data regarding a process that needs to be carried out more than 1 time. There are some special scenarios where this comes in very handy. The following are 2 of the main uses of Static variables:

  • Storing data for a procedure that is executed again later and uses that information.
  • Keeping track (counting) of a running total.

Let’s take a quick look at these 2 examples:

Example #1: Toggling

You can use a Static variable within a procedure that toggles something between 2 states.

Consider, for example, a procedure that turns bold font formatting on and off. Therefore:

  • The first time the procedure is called, bold formatting is turned on.
  • In the second execution, bold formatting is turned off.
  • For the third call, bold formatting is turned back on.
  • And so on…

Example #2: Counters

A Static variable can (also) be useful to keep track of the number of times a particular procedure is executed. You can set up such a counter by, for example:

  • Declaring a counter variable as a Static VBA variable.
  • Increasing the value assigned to the Static variable by 1 every time the procedure is called.

How To Declare A VBA Variable Using The Private And Public Statements

You can use the Private statement to declare module-level variables. In these cases, it’s an alternative to the Dim statement. I explain the topic of module-level variables in more detail below.

The fourth and final statement you can use to declare a VBA variable is Public. The Public statement is used to declare public variables. I explain public variables below.

At the beginning of this Excel tutorial, we saw that one of the defining characteristics of a VBA variable is that it is used by a program. Therefore, let’s take a look at how do you determine which program, or part of a program, can use a determined variable. We start doing this by taking a look at…

How To Determine The Scope Of A VBA Variable

The scope of a VBA variable is what determines which modules and procedures can use that particular variable. In other words, it determines where that variable can be used.

Understanding how to determine the scope of a variable is very important because:

  • A single module can have several procedures.
  • A single Excel workbooks can have several modules.

If you’re working with relatively simple VBA applications, you may only have one module with a few procedures. However, as your work with VBA starts to become more complex and sophisticated, this may change.

You may not want all of VBA variables to be accessible to every single module and procedure. At the same time, you want them to be available for the procedures that actually need them. Appropriately determining the scope of VBA variables allows you to do this.

Additionally, the scope of a VBA variable has important implications in connection with the other characteristics of the variable. An example of this is the life of a variable, a topic I explain below.

Therefore, let’s take a look at the 3 main different scopes that you can apply:

Variable Scope #1: Procedure-Level (Or Local) VBA Variables

This is the most restricted variable scope.

As implied by its name, procedure-level variables (also known as local variables) can only be used within the procedure in which they are declared. This applies to both Sub procedures and Function procedures.

In other words, when the execution of a particular procedure ends, any procedure-level variable ceases to exist. Therefore, the memory used by the variable is freed up.

The fact that Excel frees up the memory used by procedure-level variables when the procedure ends makes this type of VBA variables particularly efficient. In most cases there’s no reason to justify a variable having a broader scope than the procedure.

This is an important point: as a general rule, you should make your VBA variables as local as possible. Or, in other words: Limit a variable’s scope to the level/scope you need them.

Excel doesn’t store the values assigned to procedure-level VBA variables for use or access outside the relevant procedure. Therefore, if you call the same procedure again, any previous value of the procedure-level variables is lost.

Static variables (which I explain above) are, however, an exception to this rule. They generally retain their values after the procedure has ended.

Let’s take a look at how you declare a procedure-level variable:

As I explain above, the usual way to declare a VBA variable is by using the Dim statement. This general rule applies to procedure-level variables.

You can also use the Static statement for declaring a procedure-level variable. In such a case, you simply use the Static keyword instead of the Dim keyword when declaring the VBA variable. You’d generally use the Static statement instead of Dim if you need the variable to retain its value once the procedure has ended.

The key to making a variable procedure-level is in the location of the particular declaration statement. This statement must be within a particular procedure.

The only strict requirement regarding the location of the variable declaration statement inside a procedure is that it is before the point you use that particular VBA variable. In practice, most VBA users declare all variables at the beginning of the applicable procedure.

More precisely, the most common location of a variable declaration statement within a procedure is:

  • Immediately after the declaration statement of the relevant procedure.
  • Before the main body of statements of the relevant procedure.

The VBA code of the Variable_Test macro is a good example of how you usually declare a VBA variable using the Dim statement. Notice how the Dim statement used to declare both variables (Variable_One and Variable_Two) is between the declaration statement of the Sub procedure and the main body of statements:

VBA code to declare procedure-only variable

As you can imagine, placing all your VBA variable declaration statements at the beginning of a procedure makes the code more readable.

Since the scope of procedure-level VBA variables is limited to a particular procedure, you can use the same variable names in other procedures within the same Excel workbook or module. Bear in mind that, even though the name is the same, each variable is unique and its scope is limited to the relevant procedure.

I’m only explaining this for illustrative purposes, not to recommend that you repeat VBA variable names throughout your procedures. Repeating variable names in different procedures (inside the same project) can quickly become confusing. This is the case, particularly, when debugging those procedures. As you learn below, a common recommendation regarding variable name choice is to use unique variable names.

Let’s see how this works in practice by going back to the module containing the Variable_Test Sub procedure and adding a second (almost identical procedure): Variable_Test_Copy.

Second Sub procedure same declared VBA variables

Notice how, the only difference between the 2 Sub procedures is in the values assigned to the variables and the text that appears in the message box:

Differences in VBA Sub procedures with same variables

If I run the Variable_Test macro, Excel displays the following message box:

Example of procedure-only VBA variables

If I run the Variable_Test_Copy macro, Excel displays a very similar message box. Notice in particular how the values of Variable One and Variable Two change:

Example of procedure-only VBA variable

Let’s move on to a wider variable scope:

Variable Scope #2: Module-Level (Also Known As Private) VBA Variables

The ideas behind the concept of module-level (also known as private) VBA variables are, to a certain extent, similar to what you’ve already seen regarding procedure-level variables (with a few variations).

As implied by their name, module-level variables are available for use in any procedure within the module in which the VBA variable is declared. Therefore, module-level variables survive the termination of a particular procedure. However, they’re not available to procedures in other modules within the same VBA project.

As a consequence of the above, Excel stores the values assigned to module-level variables for use or access within the relevant module. Therefore, module-level variables retain their values between procedures, as long as those procedures are within the same module. Module-level variables allow you to pass data between procedures stored in the same module.

Despite the above, module-level variables don’t retain their values between procedures (even if they’re within the same module) if there is an End statement. As I explain below, VBA variables are purged and lose their values when VBA encounters such a statement.

The most common way to declare module-level VBA variables is by using the Dim statement. Alternatively, you can use the Private statement.

Module-level variables declared using the Dim statement are by default private. In other words, at a module-level, Dim and Private are equivalent. Therefore, you can use either.

However, some advanced VBA users suggest that using the Private statement can be a better alternative for declaring module-level variables. The reason for this is that, since you’ll generally use the Dim statement to declare procedure-level variables, using a different keyword (Private) to declare module-level variables makes the code more readable by allowing you to distinguish between procedure-level and module-level variables easily.

Just as is the case for procedure-level variables, the key to determining the scope of a module-level variable is the location of the particular declaration statement. You declare a module-level VBA variable:

  • Within the module in which you want to use the variable.
  • Outside of any of the procedures stored within the module.

The way to achieve this is simply by including the relevant variable declaration statements within the Declarations section that appears at the beginning of a module.

In the case of the sample Excel workbooks that accompany this tutorial, the Declarations section is where the Option Explicit statement appears.

Declarations section for module-only variables

You can, when working within any VBA module, easily get to the Declarations section within the Visual Basic Environment by clicking on the drop-down list on the top right corner of the Code Window (known as the Procedure Box) and selecting “(Declarations)”.

Get to Declarations section in VBE

This same drop-down list continues to display “(Declarations)” as long as you’re working within the Declarations section of the relevant module.

How to know you're in Declarations section

Let’s see the practical consequences of working with module-level variables by modifying the VBA code above as follows:

  • Making Variable_One and Variable_Two module-level variables by declaring them within the Declarations section.
  • Deleting the statements that assigned values to Variable_One and Variable_Two in the Variable_Test_Copy macro. The assignment made within the Variable_Test Sub procedure is maintained.

The resulting VBA code is as follows:

How to declare module-only variables

The following message box is displayed by Excel when the Variable_Test macro is executed:

Result of using module-only variables in VBA

And the following is the message box displayed when the Variable_Test_Copy macro is executed. Notice how both variables (Variable_One and Variable_Two):

  • Can be used in both of the procedures within the relevant module.
  • Have retained the values that were assigned by the Variable_Test macro for use in the Variable_Test_Copy macro.

Example of result obtained with module-only variables

Now, let’s take a look at the third type of variable scope:

Variable Scope #3: Public VBA Variables

The availability of public VBA variables is even broader than that of module-level variables:

  • At the basic level, public variables they are available for any procedure within any VBA module stored in the relevant Excel workbook.
  • At a more complex level, you can make public variables available to procedures and modules stored in different workbooks.

Variables that are declared with the Public statement are visible to all procedures in all modules unless Option Private Module applies. If Option Private Module is enabled, variables are only available within the project in which they are declared.

When deciding to work with public VBA variables, remember the general rule I describe above: make your VBA variables as local as possible.

Let’s start by taking a look at the basic case:

How To Declare Public VBA Variables: The Basics

In order to declare a public VBA variable, the declaration needs to meet the following conditions:

  • Be made in the Declarations section, just as you’d do when declaring a module-level variable.
  • Use the Public statement in place of the Dim statement.
  • The declaration must be made in a standard VBA module.

VBA variables whose declarations meet these conditions are available to any procedure (even those in different modules) within the same Excel workbook.

To see how this works, let’s go back to the macros above: the Variable_Test and Variable_Test_Copy macros and see how the variables (Variable_One and Variable_Two) must be declared in order to be public.

For this example, I first store both macros in different modules. Notice how, in the screenshot below, there are 2 modules shown in the Project Explorer.

vba modules public variable

Module1 stores the Variable_Test macro while Module2 stores the Variable_Test_Copy macro. The variables are declared in Module1.

This Excel VBA Variables Tutorial is accompanied by Excel workbooks containing the data and macros I use (including the macros above). You can get immediate free access to these example workbooks by subscribing to the Power Spreadsheets Newsletter.

Notice how, in the screenshot above, both variables are declared using the Dim statement. Therefore, as it stands, they’re module-level variables. If I try to execute the Variable_Test_Copy macro (which now has no variable declaration nor assignment) which is stored in Module2, Excel returns the following error message:

Error with public variable declaration

This is exactly the same error message displayed in the example above, when examining the Option Explicit statement and the reasons why you should always declare variables.

Let’s go back to Module1, where both Variable_One and Variable_Two are declared, and change the keyword used to declare them. Instead of using Dim, we use Public. The rest of the macro remains unchanged.

Declaration of public variable in VBA

If I run again both macros (Variable_Test and Variable_Test_Copy) in the same order I did above, the message boxes displayed by Excel now show the same values. More precisely:

  • When executing Variable_Test, Excel displays the following message box:

    Result of macro with public variable

  • And, since the variables are now declared using the Public statement, Excel displays the following upon the Variable_Test_Copy macro (which doesn’t declare the variables nor assigns values to them) being called.

    Execution of macro with public variable

As shown by the screenshots above:

  • Both variables are now available to all the procedures within the relevant workbook, even though they are stored in separate modules.
  • The variables retain the values assigned by the first macro (Variable_Test) for use by the second macro (Variable_Test_Copy).

This basic method of declaring public VBA variables is, in practice, the only one that you really need to know. However, in case you’re curious, let’s take a look at…

How To Declare Public VBA Variables Available Across Different Workbooks

In practice, you’ll likely only use public VBA variables that are available for all the procedures within the particular Excel workbook in which the variable is declared. This is the method I describe in the previous section.

However, it is also possible to make public VBA variables available to procedures within modules stored in different Excel workbooks. This is rarely needed (or done).

You make a variable that is available to modules stored in Excel workbooks different from that in which the variable is actually declared by following these 2 simple steps:

  • Step #1: Declare the variable as Public, following the indications in the previous section.
  • Step #2: Create a reference to the Excel workbook where the relevant variable is declared. You can set up a reference by using the References command in the Visual Basic Editor. This command appears in the Tools menu of the VBE.

Reference command for public variable

As a general rule, the scope of a variable determines its lifetime. Therefore, let’s take a look at…

What Is The Life Of A VBA Variable And How Is It Determined

The term “life” refers to how long a variable is stored in the computer’s memory.

A variable’s life is closely related to its scope. In addition to determining where a variable may be used, a variable’s scope may (in certain cases) determine the moment at which the variable is removed from the computer’s memory.

In other words: The life of a VBA variable (usually) depends on its scope.

Fortunately, the topic of variable life is simpler than that of scope. More precisely, there are 2 basic rules:

  • Rule #1: Procedure-level VBA variables declared with the Dim statement are removed from the memory when the relevant procedure finishes.
  • Rule #2: Procedure-level Static variables, module-level variables and public variables retain their values between procedure calls.

You can purge all the variables that are currently stored in memory using any of the following 3 methods:

  • Method #1: Click the Reset button.

    You can find the Reset button on the Standard toolbar within the Visual Basic Editor or within the Run menu, as shown by the images below.

    Reset button for VBA variables
    Reset button for VBA variable

  • Method #2: Click “End” when a Run-time error dialog is displayed.

    The following image shows a Run-time error caused by trying to execute a macro to delete rows if there are blank cells in a specified range without an On Error Resume Next error handler which is needed in that case. The End button is located at the bottom of the dialog.

    End button to purge VBA variable

  • Method #3: Include an End statement within your VBA code.

    From a broad point of view, the End statement has different syntactical forms. However, they one I’m referring to here is simply “End”. You can put this End statement anywhere in your code.

    The End statement can have several consequences, such as terminating code execution and closing files that were opened with the Open statement. For purposes of this Excel tutorial, the most important consequence of using the End statement is that it clears variables from the memory.

Having a good understanding of these 3 variable-purging methods is important, even if you don’t plan to use them explicitly. The reason for this is that a variable purge may cause your module-level or public variables to lose their content (even without you noticing).

Therefore, when using module-level or public variables, ensure they hold/represent the values you expect them to hold/represent.

Now that we’ve fully covered the topic of how to determine which application or part of an application can use a variable (by looking at the topics of VBA variable scope and life), let’s understand…

How To Name VBA Variables

Visual Basic for Applications provides a lot of flexibility in connection with how you can name variables. As a general matter, the rules that apply to variable naming are substantially the same rules that apply to most other elements within Visual Basic for Applications.

The main rules that apply to VBA variable naming can be summarized as follows. I also cover the topic of naming (in the context of naming procedures) within Visual Basic for Applications here and here, among other places.

  • The first character of the variable name must be a letter.
  • Characters (other than the first) can be letters, numbers, and some punctuation characters.

    One of the most commonly used punctuation characters is the underscore (_). Some VBA programmers, use it to improve the readability of VBA variable names. For illustration purposes, take a look at the macro names I use in this blog post. Other VBA users omit the underscore and use mixed case variable names (as explained below).

  • VBA variable names can’t include spaces ( ), periods (.), mathematical operators (for example +, –, /, ^ or *), comparison operators (such as =, < or >) or certain punctuation characters (such as the type-declaration characters @, #, $, %, & and ! that I explain below).
  • The names of VBA variables can’t be the same as those of any of Excel’s reserved keywords. These reserved keywords include Sub, Dim, With, End, Next and For.

    If you try to use any of this words, Excel returns a syntax error message. These messages aren’t very descriptive. Therefore, if you get a strange compile error message, it may be a good idea to confirm that you’re not using a reserved keyword to name any of your VBA variables.

    You can (theoretically) use names that match names in Excel’s VBA object model (such as Workbook, Worksheet and Range). However, this increases the risk of confusion Therefore, it is generally suggested that you avoid using such variable names.

    Similarly, consider avoiding variable names that match names used by VBA, or that match the name of built-in functions, statements or object members. Even if this practice doesn’t cause direct problems, it may prevent you from using the relevant function, statement or object member without fully qualifying the applicable reference.

    In summary: it’s best to create your own variable names, and make them unique and unambiguous.

  • Visual Basic for Applications doesn’t distinguish between upper and lowercase letters. For example, “A” is the same as “a”.

    Regardless of this rule, some VBA programmers use mixed case variable names for readability purposes. For an example, take a look at the variable names used in macro example #5, such as aRow and BlankRows.

    Some advanced VBA users suggest that it may be a good idea to start variable names with lowercase letters. This reduces the risk of confusing those names with built-in VBA keywords.

  • The maximum number of characters a VBA variable name can have is 255. However, as mentioned in Excel 2013 Power Programming with VBA, very long variable names aren’t recommended.
  • The name of each VBA variable must be unique within its relevant scope. This means that the name of a procedure-level variable must be unique within the relevant procedure, the name of a module-level variable must be unique within its module, and so on.

    This requirement makes sense if you consider how important it is to ensure that Visual Basic for Applications uses the correct variable (instead of confusing it with another one).

    At a more general level, it makes sense to have (almost) always unique names. As I explain above, re-using variable names can be confusing when debugging. Some advanced VBA users consider that there are some reasonable exceptions to this rule, such as certain control variables.

In addition to these rules, and suggestions related to those rules, you can find a few additional practices or suggestions made by Excel experts below.

For example, one of the most common suggestions regarding VBA variable naming, is to make variable names descriptive.

In some case, you can use comments to describe variables that don’t have descriptive names. I suggest, however, that you try to use descriptive variable names. They are, in my opinion, more helpful.

Finally, advanced VBA users suggest that you add a prefix to the names of VBA variables for purposes of identifying their data type. These users argue that adding these prefixes makes the code more readable and easier to modify since all variables can be easily identified as of a specific data type throughout the VBA code.

The following table shows the main tags that apply to VBA variables:

Data Type Prefix
Boolean bln
Currency cur
Double dbl
Integer int
Long lng
Single sng
String str
Type (User-Defined) typ
Variant var

In Excel 2013 Power Programming with VBA, John Walkenbach introduces a similar naming convention. In that case, the convention calls for using a lowercase prefix indicating the data type. The following table shows these prefixes (some are the same as those in the table above):

Data Type Prefix
Boolean b
Integer i
Long l
Single s
Double d
Currency c
Date/Time dt
String str
Object obj
Variant v
User-Defined u

Walkenbach doesn’t use this convention because he thinks it makes the code less readable. However, other advanced VBA users include a couple of letters at the beginning of the variable name to represent the data type.

In the end, you’ll develop your own variable-naming method that works for you. What’s more important than following the ideas of other VBA users, is to develop and (consistently) use some variable naming conventions. Please feel free to use any of the ideas and suggestions that appear (or are linked to) above when creating your variable-naming system…

And make sure to let me know your experience and ideas by leaving a comment below.

The sections above cover all the main items within the declaration statement of a VBA variable. Let’s take a quick look at what happens after you’ve declared the variable by understanding…

How To Assign A Value Or Expression To A VBA Variable

Before you assign a value to a declared VBA variable, Excel assigns the default value. Which value is assigned by default depends on the particular data type of the variable.

  • The default value for numeric data types (such as Byte, Integer, Long, Currency, Single and Double) is 0.
  • In the case of string type variables (such as String and Date), the default value is an empty string (“”), or the ASCII code 0 (or Chr(0)). This depends on whether the length of the string is variable or fixed.
  • For a Variant variable, the default value is Empty. How the Empty value is represented depends on the context:
    • In a numeric context, the Empty value is represented by 0.
    • In a string context, it’s represented by the zero-length string (“”).

As a general rule, however, you should explicitly assign a value or expression to your VBA variables instead of relying in the default values.

The statement that you use to assign a value to a VBA variable is called, fittingly, an Assignment statement. Assigning an initial value or expression to a VBA variable is also known as initializing the variable.

Assignment statements take a value or expression (yielding a string, number or object) and assign it to a VBA variable or a constant.

You’ve probably noticed that you can’t declare a VBA variable and assign a value or expression to it in the same line. Therefore, in Visual Basic for Applications, assignment statements are separate from variable declaration statements.

This Excel tutorial refers only to variables (not constants) and expressions are only covered in an introductory manner. Expressions are more useful and advanced than values. Among other strengths, expressions can be as complex and sophisticated as your purposes may require.

Additionally, if you have a good understanding of expressions, you shouldn’t have any problem with values. Therefore, let’s take a closer look at what an expression is.

Within Visual Basic for Applications, expressions can be seen as having 3 main characteristics:

  • They are composed of a combination of one or more of the following 4 elements:
    • Element #1: Keywords.
    • Element #2: Operators.
    • Element #3: Variables.
    • Element #4: Constants.
  • Their result is one of the following 3 items:
    • Item #1: A string.
    • Item #2: A number.
    • Item #3: An object.
  • They can be used for any of the following 3 purposes:
    • Purpose #1: Perform calculations.
    • Purpose #2: Manipulate characters.
    • Purpose #3: Test data.

Expressions aren’t particularly complicated. The main difference between formulas and expressions is what you do with them:

  • When using worksheet formulas, Excel displays the result they return in a cell.
  • When using expressions, you can use Visual Basic for Applications to assign the result to a VBA variable.

As a general rule, you use the equal sign (=) to assign a value or expression to a VBA variable. In other words, the equal sign (=) is the assignment operator.

When used in this context, an equal sign (=) doesn’t represent an equality. In other words, the equal sign (=) simply the assignment operator and not a mathematical symbol denoting an equality.

The basic syntax of an assignment statement using the equal sign is as follows:

  • On the right hand side of the equal sign: The value or expression you’re storing.
  • On the left hand side of the equal sign: The VBA variable where you’re storing the data.

You can change the value or expression assigned to a variable during the execution of an application.

To finish this section about Assignment statements, let’s take a quick look at the assignments made in the sample macros Variable_Test and Variable_Test_Copy. The following image shows how this (quite basic and simple) assignments were made.

Value assignment to VBA variable

Notice the use of the equal sign (=) in both cases. In both the Variable_Test and the Variable_Test_Copy macros, the value that appears on the right side of the equal sign is assigned to the variable that appears on the left side of the sign.

By now we’ve covered pretty much all the basics in connection with declaring variables in Visual Basic for Applications. You may, however, be wondering…

What if I don’t want to follow the suggestions above and don’t want to declare variables explicitly?

The following section explains how you can do this…

How To Declare VBA Variables Implicitly (a.k.a. How To Create Variables Without Declaring Them)

The first few sections of this Excel tutorial explain why declaring variables explicitly is a good idea.

However, realistically speaking, this may not be always possible or convenient. In practice, several VBA Developers don’t declare variables explicitly. In fact, these Developers tend to (simply) create variables as (and when) required.

Doing this is relatively simple and is known as declaring a variable implicitly. In practical terms, this means using a VBA variable in an assignment statement without declaring explicitly (as explained throughout most of this blog post) first. This works because, when VBA encounters a name that it doesn’t recognize (for example as a variable, reserved word, property or method), it creates a new VBA variable using that name.

Let’s take a look at a practical example by going back to the Variable_Test and Variable_Test_Copy macros…

The image below shows the VBA code of both the Variable_Test and Variable_Test_Copy macros without Variable_One and Variable_Two being ever declared explicitly. Notice how there is no Dim statement, as it is the case in the image above. Both VBA Sub procedures begin by simply assigning a value to the relevant variables.

How to declare a variable implicitly in VBA

When this happens, Visual Basic for Applications proceeds as follows:

  • Step #1: It carries out a check to confirm that there isn’t an existing variable with the same name.
  • Step #2: If there are no other variables with the same name, it creates the variable. Since the data type of the variable isn’t declared, VBA uses the default Variant type and assigns one of its sub-types.

You can, actually, set the data type of an implicitly declared variable by using type-declaration (also known as type-definition) characters. These are characters that you can add at the end of the variable name to assign the data type you want.

As explained by John Walkenbach in Excel 2013 Power Programming with VBA, type-declaration characters are a “holdover” from BASIC. He agrees that it’s generally better to declare variables using the methods I describe above.

The following table displays the main type-declaration characters you can use:

Character Data Type
% Integer
& Long
@ Currency
! Single
# Double
$ String (variable length)

For example, in the case of the Variable_Test and Variable_Test_Copy macros that appear above, you can assign the Integer data type to the variables Variable_One and Variable_Two by adding the % type-declaration character at the end of their respective names. The VBA code looks, then, as follows:

Type-declaration character when declaring variable

As shown above, you only need to include the type-declaration character once. Afterwards, you can use the variable name as usual (without type-declaration character). The following image shows how this is the case in the Variable_Test and Variable_Test_Copy macros:

Implicitly declared variable without type-declaration character

There are 2 main advantages to declaring variables implicitly as described above:

  • Advantage #1: More flexibility: By not declaring variables you are more flexible since, whenever you need a variable, you simply use it in a statement to declare it implicitly.
  • Advantage #2: You write less VBA code.

However, before you decide to start declaring your variables implicitly as explained in this section, remember the advantages of always declaring your variables and using the Option Explicit statement, and the potential problems whose origin is the lack of variable declaration.

Conclusion

Variables are a very flexible element that you’re likely to encounter constantly while working with Visual Basic for Applications. As a consequence of that flexibility and ubiquity, is important to have a good understanding of how to work with them.

Otherwise, you may eventually run into a lot of problems while debugging your VBA code. Or even worse: your macros may simply not work as intended (without you noticing) and return wrong results.

This Excel tutorial has covered the most important topics related to VBA variable declaration. Additionally, we’ve seen several different suggestions and best practices regarding work with VBA variables. Some of the most important topics covered by this VBA tutorial are the following:

  • What is a VBA variable.
  • Why is it convenient to declare VBA variables explicitly.
  • How can you remember to declare variables explicitly.
  • How to declare VBA variables taking into consideration, among others, the desired scope and life of that variable.
  • How to name variables.
  • How to assign values or expressions to VBA variables.

Finally, in case I didn’t convince you to declare your VBA variables explicitly, the last section of this Excel tutorial covered the topic of implicit variable declaration. This section provides some guidance of how to work with variables without declaring them first.

As you may have noticed, there are a lot of different opinions on the topic of best practices regarding VBA variables. As explained above, I encourage you to develop your own variable naming method.

  • See what works for you.
  • Formalize it.
  • Use it consistently.

Books Referenced In This Excel Tutorial

  • Walkenbach, John (2013). Excel 2013 Power Programming with VBA. Hoboken, NJ: John Wiley & Sons Inc.

Integer | String | Double | Boolean

This chapter teaches you how to declare, initialize and display a variable in Excel VBA. Letting Excel VBA know you are using a variable is called declaring a variable. Initializing simply means assigning a beginning (initial) value to a variable.

Place a command button on your worksheet and add the code lines below. To execute the code lines, click the command button on the sheet.

Integer

Integer variables are used to store whole numbers.

Dim x As Integer
x = 6
Range(«A1»).Value = x

Result:

Integer Variable in Excel VBA

Explanation: the first code line declares a variable with name x of type Integer. Next, we initialize x with value 6. Finally, we write the value of x to cell A1.

String

String variables are used to store text.

Code:

Dim book As String
book = «bible»
Range(«A1»).Value = book

Result:

String Variable

Explanation: the first code line declares a variable with name book of type String. Next, we initialize book with the text bible. Always use apostrophes to initialize String variables. Finally, we write the text of the variable book to cell A1.

Double

A variable of type Double is more accurate than a variable of type Integer and can also store numbers after the comma.

Code:

Dim x As Integer
x = 5.5
MsgBox «value is » & x

Result:

Not Accurate Enough

But that is not the right value! We initialized the variable with value 5.5 and we get the value 6. What we need is a variable of type Double.

Code:

Dim x As Double
x = 5.5
MsgBox «value is » & x

Result:

Double Variable

Note: Long variables have even larger capacity. Always use variables of the right type. As a result, errors are easier to find and your code will run faster.

Boolean

Use a Boolean variable to hold the value True or False.

Code:

Dim continue As Boolean
continue = True

If continue = True Then MsgBox «Boolean variables are cool»

Result:

Boolean Variable

Explanation: the first code line declares a variable with name continue of type Boolean. Next, we initialize continue with the value True. Finally, we use the Boolean variable to only display a MsgBox if the variable holds the value True.

Adding data to the worksheet is often done and it is essential to learn how to set variable to cell value in excel VBA. There can be instances when you want to add the same data to your worksheet. This task could easily be achieved with the help of Excel VBA variables. You can assign your cell values with variables. Let’s learn how to set variables to cell values in Excel VBA.

Declaring Variables in VBA

Before learning the assignment of variables, one needs to know what are variables and why they are used? Like any other programming language, VBA has variables. Variables are the containers to store data in them. There are some rules for storing data in them.

Rules for naming Variables

  • The variable name cannot start with a number.
  • While naming the variables you cannot have space between the names which means a space character (‘ ‘) is prohibited.
  • The length of the variable name should be less than Two-hundred and fifty-five (255) characters.

Implicit and Explicit Declaration

In Excel VBA, variables can be classified into 2 categories implicit and explicit,

Implicit Declaration

The implicit declaration declares a variable of data type variant. When we create variables implicitly, we never mention the data type to be used. The VBA automatically considers that variable as of variant type.

Syntax: variable_name = assigned_value

The variant data type is of two types,

  • Numeric Variant: The numeric variant data type is provided by VBA when the variable is assigned with a number. The bytes used are 16. It can take any value to Double.

Numeric-variant-data-type

  • Text Variant: The text variant data type is provided by VBA when the variable is assigned with a text. The bytes used are 22. It’s always possible to take variable sizes of the string.

Text-variant-data-type

Explicit Declaration

The explicit declaration declares a variable of custom data type. One can always mention the data type of the variable being used at the time of declaration. The keyword used is ‘Dim’.

Syntax: Dim variable_name as data_type

variable_name = assigned_value

Variable-name-as-data-type

Opening VBA immediate Window

The excel immediate window can be compared with a terminal that displays the code output in any other programming language. We will use this immediate window to run our code in the macro itself and display the code output immediately. You can also use the immediate window for debugging and running multiple VBA macros at once.

Different Ways to Open Immediate Windows in VBA

Press Ctrl + G

Open your VBA, then use the Short cut Ctrl + G on your keyboard, and the immediate window will open at the bottom side of your VBA.

Using View Tab

Step 1: Go to the Developer Tab, under the code section, and click on Visual Basic.

Clicking-visual-basic

Step 2: The VBA editor is open now.

VBA-editor-opens

Step 3: Go to View Tab, and click on Immediate Window.

Clicking-immediate-window

Step 4: The Immediate Window appears.

Immediate-window-displayed

Set Variable to Cell Value

After learning how to declare variables, and how to access the immediate window, you are ready to learn how to set variables to cell Values. Given the name of a student, ‘Arushi’. Write her Age and Aim in the worksheet by assigning variables in the VBA Macro.

Assigning-variables-in-VBA-macro

Step 1: Go to the Developer Tab, under the code section, and click on Visual Basic.

Clicking-visual-basic

Step 2: Your VBA editor is opened. Create a new Module. The name of the Sub created is geeks(). Declare an Age variable explicitly with custom data type as Integer. Assign the variable value as 19.

Variable-value-19-assigned

Step 3: Set the cell value by the variable name. Use =Range(cell).Value function to access any cell in the worksheet. Assign the Age variable to it. Run your macro.

Assigning-age-variable

Step 4: The value of cell C5 is set to 19.

Value-of-C5-set-as-19

Step 5: Repeat steps 2, 3, and 4 to set Aim for cell D5. Declare a variable name Aim explicitly with data type as Variant. Assign the variable value “CA”. Again, use the range function and set the cell value of D5 to the variable Aim.

Setting-value-of-D5-to-variable-name

Step 6: The value of cell D5 is set to “CA”.

D5-set-as-CA

Set Cell Value to Variable

We can also assign the cell values in the worksheet to the variables. Consider, the same data set as above but this time the age and aim of the student ‘Arushi’ are prefilled. Your task is to assign these values to the variables and print them in the immediate window.

Values-prefilled-shown

Step 1: Go to the Developer Tab, under the code section, and click on Visual Basic.

Clicking-visual-basic

Step 2: Declare the Age variable explicitly using the Dim keyword.

Age-variable-declared

Step 3: Assign the Age variable with the value of cell ‘C5′. This can be achieved using =Range(cell).Value function. Print the Age variable in the immediate window using Debug.Print(variable) function.

Assigning-age-variable-to-C5

Step 4: Click on the run button. The macro will run, and 19 is printed in the immediate window of the VBA.

Running-the-macro

Step 5: Repeat Steps 2, 3, and 4. Declare the Aim variable explicitly. The Range function assigns a cell value of D5 in the variable Aim. Print the Aim variable in the immediate window.

Printing-aim-variable-in-window

Step 6: Click on the run button, and “CA” is printed in the Immediate Window.

CA-printed-in-immediate-window

На чтение 25 мин. Просмотров 12.3k.

VBA Dim

Алан Перлис

Постоянная одного человека — переменная другого

Эта статья содержит полное руководство по работе с переменными и использованию VBA Dim.

Первый раздел содержит краткое руководство по использованию оператора
Dim, включая примеры и формат оператора Dim.

Остальная часть поста содержит наиболее полное руководство, которое вы
найдете в VBA Dim Statement.

Если вы заинтересованы в объявлении параметров, вы можете прочитать о
них здесь.

Содержание

  1. Краткое руководство по использованию VBA Dim Statement
  2. Полезные ссылки 
  3. Что такое VBA Dim Statement?
  4. Формат VBA Dim Statement
  5. Как использовать Dim с несколькими переменными
  6. Где я должен поместить Dim Statement?
  7. Использование Dim в циклах
  8. Могу ли я использовать Dim для присвоения значения?
  9. Dim действительно требуется?
  10. Использование Dim с Basic Variables
  11. Использование Dim с Variants
  12. Использование Dim с Objects
  13. Использование Dim с Arrays
  14. Устранение неполадок ошибок  Dim
  15. Локальные и глобальные переменные
  16. Заключение

Краткое руководство по использованию VBA Dim Statement

Описание Формат Пример
Базовая
переменная
Dim [имя
переменной] 
As [Тип]
Dim count As Long
Dim amount 
As Currency
Dim name As String
Dim visible 
As Boolean
Фиксированная
строка
Dim [имя
переменной] 
As String *[размер]
Dim s As String * 4
Dim t As String * 10
Вариант Dim [имя
переменной] 
As Variant
Dim [имя
переменной]
Dim var As Variant
Dim var
Объект
использует
Dim и New
Dim [имя
переменной] 
As New [тип объекта]
Dim coll As New 
Collection
Dim coll As New 
Class1
Объект
использует
Dim и New
Dim [имя
переменной] 
As [тип объекта]
Set [имя
переменной] = New [тип объекта]
Dim coll As Collection
Set coll = New 
Collection
Dim coll As Class1
Set coll = New Class1
Статический
массив
Dim [имя
переменной]
([первый] 
To [последний] ) 
As[Тип]
Dim arr(1 To 6) 
As Long
Динамический
массив
Dim [имя
переменной]() 
As [Тип]
ReDim [имя
переменной]
([первый] 
To [последний])
Dim arr() As Long
ReDim arr(1 To 6)
Внешняя
библиотека
(Раннее
связывание) *
Dim [имя
переменной] 
As New [пункт]
Dim dict 
As New Dictionary
Внешняя
библиотека
(Раннее
связывание с
использованием
Set) *
Dim [имя
переменной] 
As [пункт]
Set [имя
переменной] = 
New [пункт]
Dim dict As Dictionary
Set dict = 
New Dictonary 
Внешняя
библиотека
(Позднее
связывание)
Dim [имя
переменной] 
As Object
Set [имя
переменной] = CreateObject
(«[библиотека]»)
Dim dict As Object
Set dict = CreateObject(«Scripting.
Dictionary»)

* Примечание. Для раннего связывания необходимо добавить
справочный файл с помощью меню «Инструменты» -> «Ссылки». Смотрите здесь,
как добавить ссылку на Dictonary.

Полезные ссылки 

  • Объявление параметров в подпрограмме или функции
  • Использование объектов в VBA
  • Массивы VBA
  • Коллекции VBA
  • Словарь VBA
  • VBA Workbook
  • VBA Worksheet

Что такое VBA Dim Statement?

Ключевое слово Dim — это сокращение от Dimension. Он
используется для объявления переменных в VBA.

Объявление означает, что мы говорим VBA о переменной,
которую будем использовать позже.

Существует четыре типа Dim Statement. Все они очень похожи по синтаксису.

Вот они:

  1. Basic variable
  2. Variant
  3. Object
  4. Array

Ниже приводится краткое описание каждого типа

  1. Basic variable — этот тип переменной содержит одно значение. Это такие типы, как Long, String, Date, Double, Currency.
  2. Variant — VBA решает во время выполнения, какой тип будет использоваться. Вы должны избегать вариантов, где это возможно, но в некоторых случаях требуется их использование.
  3. Object — это переменная, которая может иметь несколько методов (то есть подпрограмм / функций) и несколько свойств (то есть значений). Есть 3 вида:
    Объекты Excel, такие как объекты Workbook, Worksheet и Range.
    Пользовательские объекты, созданные с использованием модулей классов.
    Внешние библиотеки, такие как Словарь.
  4. Array — это группа переменных или объектов.

В следующем разделе мы рассмотрим формат оператора VBA Dim с
некоторыми примерами каждого из них.

В последующих разделах мы рассмотрим каждый тип более
подробно.

Формат VBA Dim Statement

Формат выражения Dim показан ниже.

' 1. BASIC VARIABLE
' Объявление основной переменной
Dim [Имя переменной] As [тип]

' Объявление фиксированной строки
Dim [Имя переменной] As String * [размер]

' 2. VARIANT
Dim [Имя переменной] As Variant
Dim [Имя переменной]

' 3. OBJECT
' Объявление объекта
Dim [Имя переменной] As [тип]

' Объявление и создание объекта
Dim [Имя переменной] As New [тип]

' Объявление объекта с использованием позднего связывания
Dim [Имя переменной] As Object

' 4. ARRAY
' Объявление статического массива
Dim [Имя переменной](first To last) As [тип]

' Объявление динамического массива
Dim [Имя переменной]() As [тип]
Ниже приведены примеры использования различных форматов.
Sub Primeri()

    ' 1. BASIC VARIABLE
    ' Объявление основной переменной
    Dim name As String
    Dim count As Long
    Dim amount As Currency
    Dim eventdate As Date
    
    ' Объявление фиксированной строки
    Dim userid As String * 8
    
    ' 2. VARIANT
    Dim var As Variant
    Dim var
    
    ' 3. OBJECT
    ' Объявление объекта
    Dim sh As Worksheet
    Dim wk As Workbook
    Dim rg As Range
    
    ' Объявление и создание объекта
    Dim coll1 As New Collection
    Dim o1 As New Class1
    
    ' Объявление объекта - создайте объект ниже, используя Set
    Dim coll2 As Collection
    Dim o2 As Class1
    
    Set coll2 = New Collection
    Set o2 = New Class1
    
    ' 	Объявление и присвоение с использованием позднего связывания
    Dim dict As Object
    Set dict = CreateObject("Scripting.Dictionary")
    
    ' 4. ARRAY
    ' Объявление статического массива
    Dim arrScores(1 To 5) As Long
    Dim arrCountries(0 To 9) As String
    
    ' Объявление динамического массива - установите размер ниже, используя ReDim
    Dim arrMarks() As Long
    Dim arrNames() As String
    
    ReDim arrMarks(1 To 10) As Long
    ReDim arrNames(1 To 10) As String

End Sub

Мы рассмотрим эти различные типы операторов Dim в следующих
разделах.

Как использовать Dim с несколькими переменными

Мы можем объявить несколько переменных в одном выражении Dim.

Dim name As String, age As Long, count As Long

Если мы опускаем тип, то VBA автоматически устанавливает тип как Variant. Мы увидим больше
о Variant позже.

' Сумма является вариантом
Dim amount As Variant

' Сумма является вариантом
Dim amount

' Адрес это вариант - имя это строка
Dim name As String, address

' имя - это вариант, адрес – строка
Dim name, address As String

Когда вы объявляете несколько переменных, вы должны указать тип каждой отдельно.

Dim wk As Workbook, marks As Count, name As String

Вы можете поместить столько переменных, сколько захотите, в
одном выражении Dim, но
для удобства чтения рекомендуется оставить его равным 3 или 4.

Где я должен поместить Dim Statement?

Оператор Dim может быть помещен в любое место кода. Тем не менее, он должен предшествовать любой строке, где используется переменная.

Если переменная используется перед оператором Dim, вы получите ошибку
«переменная не определена»

Dim statements

Когда дело доходит до позиционирования ваших Dim утверждений, вы можете сделать это двумя основными способами. Вы можете разместить все свои Dim заявления в верхней части процедуры.

Sub DimVverh()

    ' Размещение всех Dim statements наверху
    Dim count As Long, name As String, i As Long
    Dim wk As Workbook, sh As Worksheet, rg As Range
    
    Set wk = Workbooks.Open("C:ДокументыОтчет.xlsx")
    Set sh = wk.Worksheets(1)
    Set rg = sh.Range("A1:A10")
    
    For i = 1 To rg.Rows.count
        count = rg.Value
        Debug.Print count
    Next i
  
End Sub

ИЛИ вы можете объявить переменные непосредственно перед их
использованием:

Sub DimIsp()

    Dim wk As Workbook
    Set wk = Workbooks.Open("C:ДокументыОтчет.xlsx")
    
    Dim sh As Worksheet
    Set sh = wk.Worksheets(1)
    
    Dim rg As Range
    Set rg = sh.Range("A1:A10")
    
    Dim i As Long, count As Long, name As String
    For i = 1 To rg.Rows.count
        count = rg.Value
        name = rg.Offset(0, 1).Value
        Debug.Print name, count
    Next i
  
End Sub

Я лично предпочитаю последнее, так как оно делает код более
аккуратным, и его легче читать, обновлять и обнаруживать ошибки.

Использование Dim в циклах

Помещение оператора Dim в цикл не влияет на переменную.

Когда VBA запускает Sub (или Function), первым делом он
создает все переменные, которые были объявлены в выражениях Dim.

Следующие 2 фрагмента кода практически одинаковы. Во-первых,
переменная Count объявляется перед циклом. Во втором он объявлен в цикле.

Sub CountPeredCiklom()

    Dim count As Long

    Dim i As Long
    For i = 1 To 3
        count = count + 1
    Next i
    
    ' значение счета будет 3
    Debug.Print count

End Sub
Sub CountPosleCikla()

    Dim i As Long
    For i = 1 To 3
        Dim count As Long
        count = count + 1
    Next i
    
    ' значение счета будет 3
    Debug.Print count

End Sub

Код будет вести себя точно так же, потому что VBA создаст переменные при
входе в подпрограмму.

Могу ли я использовать Dim для присвоения значения?

В таких языках, как C ++, C # и Java, мы можем объявлять и назначать переменные в одной строке:

' C++
int i = 6
String name = "Иван"

Мы не можем сделать это в VBA. Мы можем использовать оператор двоеточия для размещения
объявлений и назначения строк в одной строке.

Dim count As Long: count = 6

Мы не объявляем и не присваиваем в одной строке VBA. Что мы
делаем, это помещаем эти две строки (ниже) в одну строку в редакторе. Что
касается VBA, это две отдельные строки, как здесь:

Dim count As Long
count = 6

Здесь мы помещаем 3 строки кода в одну строку редактора,
используя двоеточие:

count = 1: count = 2: Set wk = ThisWorkbook

Нет никаких преимуществ или недостатков в назначении и
объявлении в одной строке редактора. Все сводится к личным предпочтениям.

Dim действительно требуется?

Ответ в том, что это не обязательно. VBA не требует от вас
использовать Dim Statement.

Однако не использовать оператор Dim — плохая практика и
может привести к множеству проблем.

Вы можете использовать переменную без предварительного
использования оператора Dim. В этом случае переменная автоматически будет типом
варианта.

Это может привести к таким проблемам, как

  1. Все переменные являются вариантами (проблемы с
    этим см. В разделе «Варианты»).
  2. Некоторые переменные ошибки останутся
    незамеченными.

Из-за этих проблем рекомендуется сделать использование Dim
обязательным в нашем коде. Мы делаем это с помощью оператора Option Explicit.

Option Explicit

 Мы можем сделать Dim
обязательным в модуле, набрав «Option Explicit» в верхней части модуля.

Мы можем сделать это автоматически в каждом новом модуле,
выбрав Tools-> Options из меню и отметив флажок «Требовать декларацию
переменной». Затем, когда вы вставите новый модуль, «Option Explicit» будет
автоматически добавлен в начало.

VBA Require Variable Declaration

Давайте посмотрим на некоторые ошибки, которые могут
остаться незамеченными, если мы не будем использовать Dim.

Ошибки Переменной

В приведенном ниже коде мы используем переменную Total без использования оператора Dim.

Sub BezDim()

    Total = 6
    
    Total = Total + 1
    
    Debug.Print Total

End Sub

Если мы случайно написали Total неправильно, VBA сочтет это
новой переменной.

В приведенном ниже коде мы неправильно написали переменную Total как Totall.

Sub BezDimOshibki()

    Total = 6
    
    ' Первый Total - это ошибка
    Totall = Total + 1
    
    ' напечатает 6 вместо 7
    Debug.Print Total

End Sub

VBA не обнаружит ошибок в коде, и будет напечатано неверное
значение.

Давайте добавим Option Explicit и попробуйте приведенный
выше код снова

Option Explicit 

Sub BezDimOshibki()

    Total = 6
    
    ' Первый Total - это ошибка
    Totall = Total + 1
    
    ' Напечатает 6 вместо 7
    Debug.Print Total

End Sub

Теперь, когда мы запустим код, мы получим ошибку «Переменная
не определена». Чтобы эта ошибка не появлялась, мы должны использовать Dim для каждой переменной,
которую мы хотим использовать.

Когда мы добавим оператор Dim для Total
и запустим код, мы получим ошибку, сообщающую, что опечатка Totall не была определена.

variable not defined 2

Это действительно полезно, так как помогает нам найти
ошибку, которая в противном случае осталась бы незамеченной.

Ошибка в ключевом слове

Вот второй пример, который более тонкий.

Когда следующий код выполняется, он должен изменить шрифт в
ячейке A1 на синий.

Однако, когда код запускается, ничего не происходит.

Sub ZadatCvet()

    Sheet1.Range("A1").Font.Color = rgblue

End Sub

Ошибка здесь в том, что rgblue должен быть rgbBlue. Если вы
добавите Option Explicit в модуль, появится ошибка «переменная не определена».
Это значительно облегчает решение проблемы.

Эти два примера очень просты. Если у вас много кода, то
подобные ошибки могут стать кошмаром для отслеживания.

Использование Dim с Basic Variables

VBA имеет те же основные типы переменных, которые
используются в электронной таблице Excel.

Вы можете увидеть список всех типов переменных VBA здесь.

Тем не менее, большую часть времени вы будете использовать следующие:

Тип Хранение Диапазон Описание
Boolean 2 байта ИСТИНА или ЛОЖЬ Эта переменная
может быть
ИСТИНА или
ЛОЖЬ.
Long 4 байта от -2,147,483,648
до 2,147,483,647
Long — это
сокращение от
Long Integer.
Используйте это
вместо
типа Integer *
Currency 8 байт от -1,79769313486231E308
до -4,94065645841247E-324
для отрицательных
значений;
от 4.94065645841247E-324
до 1.79769313486232E308
для положительных
значений
Аналогично
Double,
но имеет
только 4
знака после
запятой
Double 8 байт от -922,337,203,685,477.5808
до 922,337,203,685,477.5807
Date 8 байт С 1 января 100
по 31 декабря 9999
String меняется От 0 до примерно
2 миллиардов
Содержит
текст

* Первоначально мы использовали бы тип Long вместо Integer,
потому что Integer был 16-разрядным, и поэтому диапазон был от -32 768 до 32
767, что довольно мало для многих случаев использования целых чисел.

Однако в 32-битной (или выше) системе целое число автоматически
преобразуется в длинное. Поскольку Windows была 32-битной начиная с Windows 95
NT, нет смысла использовать Integer.

В двух словах, всегда используйте Long для целочисленного
типа в VBA.

Фиксированный тип строки

В VBA есть один необычный тип базовой переменной, с которым
вы, возможно, не знакомы.

Это фиксированный тип строки. Когда мы создаем нормальную строку в VBA, мы можем добавить текст, и VBA автоматически изменит размер строки для нас.

Sub TipStroki()

    Dim s As String
    
    ' s is "Иван Петров"
    s = "John Smith"
    
    ' s is "Игорь"
    s = "Tom"

End Sub

Фиксированная строка никогда не изменяется. Эта строка
всегда будет иметь одинаковый размер независимо от того, что вы ей назначаете

вот несколько примеров:

Sub FiksStroka()
    
    Dim s As String * 4
    
    ' s is "Иван"
    s = "Иван Перов"
    
    ' s = "Игорь "
    s = "Игорь"

End Sub

Использование Dim с Variants

Когда мы объявляем переменную как вариант, VBA решает во время выполнения, какой
тип переменной должен быть.

Мы объявляем варианты следующим образом

' Оба варианта
Dim count
Dim count As Variant
Это звучит как отличная идея в теории. Больше не нужно беспокоиться о типе переменной
Sub IspVariants()
    
    Dim count As Variant
        
    count = 7
    
    count = "Иван"
    
    count = #12/1/2018#

End Sub

Однако использование вариантов является плохой практикой, и
вот почему:

  1. VBA
    не будет замечать неправильных ошибок типа (т. Е. Несоответствие данных).
  2. Вы не можете получить доступ к Intellisense.
  3. VBA
    угадывает лучший тип, и это может быть не то, что вы хотите.

Тип ошибки

Ошибки твои друзья!

Они могут раздражать и расстраивать, когда они случаются, но
они предупреждают вас о будущих проблемах, которые не так легко найти.

Ошибка несоответствия типов предупреждает вас, когда используются неверные данные.

Например. Представьте, что у нас есть лист оценок учеников.
Если кто-то случайно (или намеренно) заменит метку на текст, данные будут
недействительными.

Если мы используем вариант для хранения меток, то ошибки не
возникнет

Sub MarksVariant()
    
    Dim marks As Variant
    
    Dim i As Long
    For i = 1 To 10
        
        ' Прочитайте отметку
        mark = Sheet1.Range("A" & i).Value
        
    Next

End Sub

Это не хорошо, потому что в ваших данных есть ошибка, а вы
не знаете об этом.

Если вы зададите переменную Long, VBA сообщит вам об ошибке
«Несоответствие типов», если значения являются текстовыми.

Sub MarksLong()
    
    Dim mark As Long
    
    Dim i As Long
    For i = 1 To 10
        
        ' Прочитайте отметку
        mark = Sheet1.Range("A" & i).Value
        
    Next

End Sub

Доступ к Intellisense

Intellisense — удивительная особенность VBA. Он дает вам
доступные параметры в зависимости от типа, который вы создали.

Представьте, что вы объявляете переменную листа, используя
Dim

Когда вы используете переменную wk с десятичной точкой, VBA
автоматически отобразит доступные опции для переменной.

Вы можете увидеть Intellisense на скриншоте ниже

VBA Intellisense

Если вы используете Variant как тип, то Intellisense будет
недоступен

Это потому, что VBA не будет знать тип переменной до времени
выполнения.

Использование Dim с Objects

Если вы не знаете, что такое Objects, вы можете прочитать
мою статью об VBA Objects здесь.

Есть 3 типа объектов:

  1. Объекты Excel
  2. Объекты модуля класса
  3. Внешние объекты библиотеки

Примечание. Объект VBA Collection используется аналогично тому, как мы используем объект Class Module. Мы используем новое, чтобы создать его.

Давайте посмотрим на каждый из них по очереди.

Объекты Excel

Объекты Excel, такие как Рабочая книга, Рабочий лист,
Диапазон и т. Д., Не используют Новый, поскольку они автоматически создаются
Excel. Смотрите, «когда New не требуется».

При создании или открытии книги Excel автоматически создает
связанный объект.

Например, в приведенном ниже коде мы открываем рабочую
книгу. VBA создаст объект, а функция Open вернет книгу, которую мы можем
сохранить в переменной

Sub OtkrWorkbook()
    
    Dim wk As Workbook
    Set wk = Workbooks.Open("C:ДокументыОтчет.xlsx")

End Sub

Если мы создадим новый лист, произойдет похожая вещь. VBA
автоматически создаст его и предоставит доступ к объекту.

Sub DobavSheet()
    
    Dim sh As Worksheet
    Set sh = ThisWorkbook.Worksheets.Add

End Sub

Нам не нужно использовать ключевое слово New для этих объектов Excel.

Мы просто присваиваем переменную функции, которая либо
создает новый объект, либо дает нам доступ к существующему.

Вот несколько примеров назначения переменных Workbook, Worksheet и range

Sub DimWorkbook()
    
    Dim wk As Workbook
    
    ' назначить wk новой книге
    Set wk = Workbooks.Add
    
    ' назначить wk первой открытой книге
    Set wk = Workbooks(1)
    
    ' назначить wk рабочей книге Отчет.xlsx
    Set wk = Workbooks("Отчет.xlsx")
    
    ' назначить wk активной книге
    Set wk = ActiveWorkbook
    
End Sub
Sub DimWorksheet()
    
    Dim sh As Worksheet
    
    ' Назначить sh на новый лист
    Set sh = ThisWorkbook.Worksheets.Add
    
    ' Назначьте sh на крайний левый лист
    Set sh = ThisWorkbook.Worksheets(1)
    
    ' Назначьте sh на лист под названием «Клиенты»
    Set sh = ThisWorkbook.Worksheets("Клиенты")
    
    ' Присвойте sh активному листу
    Set sh = ActiveSheet

End Sub
Sub DimRange()

    ' Получить рабочий лист клиента
    Dim sh As Worksheet
    Set sh = ThisWorkbook.Worksheets("Клиенты")
    
    ' Объявите переменную диапазона
    Dim rg As Range
    
    ' Присвойте rg диапазону A1
    Set rg = sh.Range("A1")
    
    ' Назначьте rg в диапазоне от B4 до F10
    Set rg = sh.Range("B4:F10")
    
    ' Присвойте rg диапазону E1
    Set rg = sh.Cells(1, 5)
    
End Sub

Если вы хотите узнать больше об этих объектах, вы можете ознакомиться со следующими статьями: Workbook VBA, Worksheet VBA и Cell и Range VBA.

Использование Dim с Class Module Objects

В VBA мы используем Class Modules для создания наших собственных пользовательских объектов. Вы можете прочитать все о Class Modules здесь.

Если мы
создаем объект, нам нужно использовать ключевое слово New.

Мы можем сделать это в операторе Dim или в операторе Set.

Следующий код создает объект, используя ключевое слово New в выражении Dim:

' Объявить и создать
Dim o As New class1
Dim coll As New Collection

Использование New в выражении Dim означает, что каждый раз
при запуске нашего кода будет создаваться ровно один объект.

Использование Set дает нам больше гибкости. Мы можем создать
много объектов из одной переменной. Мы также можем создать объект на основе
условия.

Этот следующий код показывает, как мы создаем объект Class Module, используя Set. (Чтобы создать модуль класса, перейдите в окно проекта, щелкните правой кнопкой мыши соответствующую книгу и выберите «Вставить модуль класса». Подробнее см. «Создание Simple Class Module».)

' Объявить только
Dim o As Class1

' Создать с помощью Set
Set o = New Class1

Давайте посмотрим на пример использования Set. В приведенном ниже коде мы хотим
прочитать диапазон данных. Мы создаем объект только в том случае, если значение
больше 50.

Мы используем Set для создания объекта Class1. Это потому, что количество нужных нам объектов зависит от
количества значений более 50.

Sub IspSet()
    
    ' Объявите переменную объекта Class1
    Dim o As Class1
    
    ' Читать диапазон
    Dim i As Long
    For i = 1 To 10
        If Sheet1.Range("A" & i).Value > 50 Then

            ' Создать объект, если условие выполнено
            Set o = New Class1
            
        End If
    Next i

End Sub

Я сохранил этот пример простым для ясности. В реальной версии этого кода мы бы заполнили объект Class Module данными и добавили его в структуру данных, такую как Collection или Dictionary.

Вот пример реальной версии, основанной на данных ниже:

dim sample data

' Class Module - clsStudent
Public Name As String
Public Subject As String

' Стандартный модуль
Sub ChitatBalli()

    ' Создать коллекцию для хранения объектов
    Dim coll As New Collection
    
    ' Current Region получает соседние данные
    Dim rg As Range
    Set rg = Sheet1.Range("A1").CurrentRegion
    
    Dim i As Long, oStudent As clsStudent
    For i = 2 To rg.Rows.Count
        
        ' Проверьте значение
        If rg.Cells(i, 1).Value > 50 Then
            ' Создать новый объект
            Set oStudent = New clsStudent
            
            ' Читать данные на объект студента
            oStudent.Name = rg.Cells(i, 2).Value
            oStudent.Subject = rg.Cells(i, 3).Value
            
            ' добавить объект в коллекцию
            coll.Add oStudent
            
        End If
        
    Next i
    
    ' Распечатайте данные в Immediate Window, чтобы проверить их
    Dim oData As clsStudent
    For Each oData In coll
        Debug.Print oData.Name & " studies " & oData.Subject
    Next oData

End Sub

Чтобы узнать больше о Set вы можете заглянуть сюда.

Объекты из внешней библиотеки

Действительно полезная часть VBA — это то, как у нас есть
доступ к внешним библиотекам. Это открывает целый новый мир тому, что мы можем
сделать.

Примерами являются библиотеки Access, Outlook и Word,
которые позволяют нам взаимодействовать с этими приложениями.

Мы можем использовать библиотеки для различных типов
структур данных, таких как Словарь, Массив, Стек и Очередь.

Существуют библиотеки для очистки веб-сайта (библиотека
объектов Microsoft HTML), использования регулярных выражений (регулярные
выражения Microsoft VBScript) и многих других задач.

Мы можем создать эти объекты двумя способами:

  1. Раннее связывание
  2. Позднее связывание

Давайте посмотрим на это по очереди.

Раннее связывание

Раннее связывание означает, что мы добавляем справочный
файл. Как только этот файл добавлен, мы можем рассматривать объект как объект
модуля класса.

Мы добавляем ссылку, используя Tools-> Reference, а затем
проверяем соответствующий файл в списке.

Например, чтобы использовать словарь, мы ставим флажок
«Microsoft Scripting Runtime»

vba references dialog

Как только мы добавим ссылку, мы можем использовать словарь
как объект модуля класса

Sub RanSvyaz()

    ' Используйте только Dim
    Dim dict1 As New Dictionary
    
    ' Используйте Dim и Set
    Dim dict2 As Dictionary
    Set dict2 = New Dictionary

End Sub

Преимущество раннего связывания заключается в том, что у нас
есть доступ к Intellisense. Недостатком является то, что это может вызвать
конфликтные проблемы на других компьютерах.

Лучше всего использовать раннюю привязку при написании кода,
а затем использовать позднюю привязку при распространении кода другим
пользователям.

Позднее связывание

Позднее связывание означает, что мы создаем объект во время
выполнения.

Мы объявляем переменную как тип «Объект». Затем мы
используем CreateObject для создания объекта.

Sub PozdSvyaz()

    Dim dict As Object
    Set dict = CreateObject("Scripting.Dictionary")
    
End Sub

Использование Dim с Arrays

В VBA есть два типа массивов:

  1. Статический — размер массива задается в
    операторе Dim и не может изменяться.
  2. Динамический — размер массива не указан в
    выражении Dim. Это устанавливается позже с помощью оператора ReDim
' Статический массив

' Магазины 7 длинных - от 0 до 6
Dim arrLong(0 To 6) As Long

' Магазины 7 длинных - от 0 до 6
Dim arrLong(6) As String

Динамический массив дает нам гораздо больше гибкости. Мы
можем установить размер во время выполнения кода.

Мы объявляем динамический массив, используя инструкцию Dim,
и устанавливаем размер позже, используя ReDim.

' Динамический массив

' Объявите переменную
Dim arrLong() As Long

' Установить размер
ReDim arrLong(0 To 6) As Long

Использование ReDim

Большая разница между Dim и ReDim
заключается в том, что мы можем использовать переменную в выражении ReDim. В операторе Dim размер должен быть
постоянным значением.

Sub IspSet()

    ' Объявите переменную
    Dim arrLong() As Long
    
    ' Спросите пользователя о размере
    Dim size As Long
    size = InputBox("Пожалуйста, введите размер массива.", Default:=1)
    
    ' Установите размер на основе пользовательского ввода
    ReDim arrLong(0 To size) As Long

End Sub

На самом деле мы можем использовать оператор Redim без
предварительного использования оператора Dim.

В первом примере вы можете видеть, что мы используем Dim:

Sub IspDimReDim()

    ' Использование Dim
    Dim arr() As String

    ReDim arr(1 To 5) As String
    
    arr(1) = "Яблоко"
    arr(5) = "Апельсин"
    
End Sub

Во втором примере мы не используем Dim:

Sub IspTolkoReDim ()

    ' Использование только ReDim
    ReDim arr(1 To 5) As String
    
    arr(1) = "Яблоко"
    arr(5) = "Апельсин"
    
End Sub

Преимущество состоит в том, что вам не нужно тусклое
утверждение. Недостатком является то, что это может сбить с толку тех, кто
читает ваш код. В любом случае это не имеет большого значения.

Вы можете использовать ключевое слово Preserve с ReDim для сохранения существующих данных при изменении размера массива. Вы можете прочитать больше об этом здесь.

Вы можете найти все, что вам нужно знать о массивах в VBA здесь.

Устранение неполадок ошибок  Dim

В таблице
ниже приведены ошибки, с которыми вы можете столкнуться при использовании Dim. См. Ошибки VBA для
объяснения различных типов ошибок.

Ошибка Тип Причина
Массив уже
рассчитан
Компиляция Использование
Redim для
статического
массива.
Ожидаемый:
идентификатор
Синтаксис Использование
зарезервированного слова в качестве
имени переменной.
Ожидаемый:
новый тип имени
Синтаксис Тип отсутствует в
выражении Dim.
Переменная объекта или переменная
блока не
установлена
Время выполнения New не был
использован для
создания объекта.
Переменная объекта или переменная
блока
не установлена
Время выполнения Set не использовался для назначения
переменной объекта.
Пользовательский
тип не определен
Компиляция Тип не распознан.
Это может
произойти, если
ссылочный файл не добавлен в меню
«Инструменты->
Ссылка» или имя
модуля класса
написано
неправильно.
Недопустимый
оператор вне блока
Type
Компиляция Имя переменной
отсутствует в
выражении Dim
Переменная
не определена
Компиляция Переменная
используется перед Dim-строкой.

Локальные и глобальные переменные

Когда мы используем Dim в процедуре (то есть подпрограмме или функции), она считается
локальной. Это означает, что это доступно только с этой процедурой.

Глобальные переменные объявляются вне процедур. В
зависимости от типа, они могут быть доступны для всех процедур в одном и том же
модуле или для всех процедур во всех модулях в текущей рабочей книге.

В приведенном ниже коде мы объявили count как глобальную переменную:

' Глобальная
Dim count As Long
Sub UseCount1()
    count = 6
End Sub
Sub UseCount2()
    count = 4
End Sub

Что произойдет, если у нас будет глобальная переменная и
локальная переменная с одинаковым именем?

На самом деле это не вызывает ошибку. VBA дает приоритет локальной декларации.

' Глобальная
Dim count As Long

Sub UseCount()
    ' Локальная
    Dim count As Long
    
    ' Относится к локальному счету
    count = 6
    
End Sub

Подобная ситуация может привести только к проблемам, так как
трудно отследить, какой счет используется.

Вообще глобальных переменных следует избегать, где это
возможно. Они делают код очень трудным для чтения, потому что их значения могут
быть изменены в любом месте кода. Это затрудняет обнаружение и устранение ошибок.

Важно знать и понимать глобальные переменные как вы,
поскольку вы можете встретить их в существующем коде.

Dim против Private

В VBA есть ключевое слово Private.

Если мы используем ключевое слово Private с переменной или
подфункцией / функцией, то этот элемент доступен только в текущем модуле.

Использование Dim и Private для переменной дает тот же
результат

' Доступно во всем этом модуле
Private priCount As Long
Dim dimCount As Long

Sub UseCount()

    ' Доступно только в этом разделе
    Private priName As String
    Dim dimName As String
    
End Sub

В VBA принято использовать Private для глобальных переменных
и Dim для локальных

' Доступно во всем этом модуле
Private priCount As Long

Sub UseCount()
    ' Только локальный
    Dim dimName As String
    
End Sub

Local OnlyThere
в VBA есть 2 других
типа объявлений, которые называются Public и Global.

Ниже приводится краткое изложение всех 4 типов:

  1. Dim
    — используется для объявления локальных переменных, т. Е. В процедурах.
  2. Private
    — используется для объявления глобальных переменных и процедур. Эти переменные
    доступны только для текущего модуля.
  3. Public
    — используется для объявления глобальных переменных и процедур. Эти переменные
    доступны во всех модулях.
  4. Global
    — старая и устаревшая версия Public.
    Может использоваться только в стандартных модулях. Он существует только для обратной
    совместимости.

Заключение

На этом мы заканчиваем статью о VBA Dim Statement. Если у вас есть
какие-либо вопросы или мысли, пожалуйста, дайте мне знать в комментариях ниже.

“One man’s constant is another man’s variable.” – Alan Perlis

This post provides a complete guide to using the VBA Dim statement.

The first section provides a quick guide to using the Dim statement including examples and the format of the Dim statement.

The rest of the post provides the most complete guide you will find on the VBA Dim Statement.

If you are interested in declaring parameters then you can read about them here.

A Quick Guide to using the VBA Dim Statement

Description Format Example
Basic variable Dim [variable name] As [Type] Dim count As Long
Dim amount As Currency
Dim name As String
Dim visible As Boolean
Fixed String Dim [variable name] As String * [size] Dim s As String * 4
Dim t As String * 10
Variant Dim [variable name] As Variant
Dim [variable name]
Dim var As Variant
Dim var
Object using Dim and New Dim [variable name] As New [object type] Dim coll As New Collection
Dim coll As New Class1
Object using Dim, Set and New Dim [variable name] As [object type]
Set [variable name] = New [object type]
Dim coll As Collection
Set coll = New Collection

Dim coll As Class1
Set coll = New Class1

Static array Dim [variable name]([first] To [last] ) As [Type] Dim arr(1 To 6) As Long
Dynamic array Dim [variable name]() As [Type]
ReDim [variable name]([first] To [last])
Dim arr() As Long
ReDim arr(1 To 6)
External Library
(Early Binding)*
Dim [variable name] As New [item] Dim dict As New Dictionary
External Library
(Early Binding using Set)*
Dim [variable name] As [item]
Set [variable name] = New [item]
Dim dict As Dictionary
Set dict = New Dictonary
External Library
(Late Binding)
Dim [variable name] As Object
Set [variable name] = CreateObject(«[library]»)
Dim dict As Object
Set dict = CreateObject(«Scripting.Dictionary»)

*Note: Early binding requires that you add the reference file using Tools->References from the menu. See here for how to add the Dictonary reference.

Useful Links

Declaring parameters in a sub or function
Using Objects in VBA
VBA Arrays
VBA Collection
VBA Dictionary
VBA Workbook
VBA Worksheet

What is the VBA Dim Statement

The Dim keyword is short for Dimension. It is used to declare variables in VBA.

Declare means we are telling VBA about a variable we will use later.

There are four types of Dim statements. They are all pretty similar in terms of syntax.

They are:

  1. Basic variable
  2. Variant
  3. Object
  4. Array

The following is a brief description of each type:

    1. Basic variable – this variable type holds one value. These are the types such as Long, String, Date, Double, Currency.
    1. Variant – VBA decides at runtime which type will be used. You should avoid variants where possible but in certain cases it is a requirement to use them.
    1. Object – This is a variable that can have multiple methods(i.e. subs/functions) and multiple properties(i.e. values). There are 3 kinds:
      1. Excel objects such as the Workbook, Worksheet and Range objects.
      2. User objects created using Class Modules.
      3. External libraries such as the Dictionary.
  1. Array – this is a group of variables or objects.

In the next section, we will look at the format of the VBA Dim statement with some examples of each.

In later sections we will look at each type in more detail.

Format of the VBA Dim Statement

The format of the Dim statement is shown below

' 1. BASIC VARIABLE
' Declaring a basic variable
Dim [variable name] As [type]

' Declaring a fixed string
Dim [variable name] As String * [size]

' 2. VARIANT
Dim [variable name] As Variant
Dim [variable name]

' 3. OBJECT
' Declaring an object
Dim [variable name] As [type]

' Declaring and creating an object
Dim [variable name] As New [type]

' Declaring an object using late binding
Dim [variable name] As Object

' 4. ARRAY
' Declaring a static array
Dim [variable name](first To last) As [type]

' Declaring a dynamic array
Dim [variable name]() As [type]

Below are examples of using the different formats

' https://excelmacromastery.com/
Sub Examples()

    ' 1. BASIC VARIABLE
    ' Declaring a basic variable
    Dim name As String
    Dim count As Long
    Dim amount As Currency
    Dim eventdate As Date
    
    ' Declaring a fixed string
    Dim userid As String * 8
    
    ' 2. VARIANT
    Dim var As Variant
    Dim var
    
    ' 3. OBJECT
    ' Declaring an object
    Dim sh As Worksheet
    Dim wk As Workbook
    Dim rg As Range
    
    ' Declaring and creating an object
    Dim coll1 As New Collection
    Dim o1 As New Class1
    
    ' Declaring an object - create object below using Set
    Dim coll2 As Collection
    Dim o2 As Class1
    
    Set coll2 = New Collection
    Set o2 = New Class1
    
    ' Declaring and assigning using late binding
    Dim dict As Object
    Set dict = CreateObject("Scripting.Dictionary")
    
    ' 4. ARRAY
    ' Declaring a static array
    Dim arrScores(1 To 5) As Long
    Dim arrCountries(0 To 9) As String
    
    ' Declaring a dynamic array - set size below using ReDim
    Dim arrMarks() As Long
    Dim arrNames() As String
    
    ReDim arrMarks(1 To 10) As Long
    ReDim arrNames(1 To 10) As String

End Sub

We will examine these different types of Dim statements in the later sections.

How to Use Dim with Multiple Variables

We can declare multiple variables in a single Dim statement

Dim name As String, age As Long, count As Long

If we leave out the type then VBA automatically sets the type to be a Variant. We will see more about Variant later.

' Amount is a variant
Dim amount As Variant

' Amount is a variant
Dim amount

' Address is a variant - name is a string
Dim name As String, address

' name is a variant, address is a string
Dim name, address As String

When you declare multiple variables you should specify the type of each one individually

Dim wk As Workbook, marks As Long, name As String

You can place as many variables as you like in one Dim statement but it is good to keep it to 3 or 4 for readability.

Where Should I Put the Dim Statement?

The Dim statement can be placed anywhere in a procedure. However, it must come before any line where the variable is used.

If the variable is used before the Dim statement then you will get a “variable not defined” error:

When it comes to the positioning your Dim statements you can do it in two main ways. You can place all your Dim statements at the top of the procedure:

' https://excelmacromastery.com/
Sub DimTop()

    ' Placing all the Dim statements at the top
    Dim count As Long, name As String, i As Long
    Dim wk As Workbook, sh As Worksheet, rg As Range
    
    Set wk = Workbooks.Open("C:Docsdata.xlsx")
    Set sh = wk.Worksheets(1)
    Set rg = sh.Range("A1:A10")
    
    For i = 1 To rg.Rows.count
        count = rg.Value
        Debug.Print count
    Next i
  
End Sub

OR you can declare the variables immediately before you use them:

' https://excelmacromastery.com/
Sub DimAsUsed()

    Dim wk As Workbook
    Set wk = Workbooks.Open("C:Docsdata.xlsx")
    
    Dim sh As Worksheet
    Set sh = wk.Worksheets(1)
    
    Dim rg As Range
    Set rg = sh.Range("A1:A10")
    
    Dim i As Long, count As Long, name As String
    For i = 1 To rg.Rows.count
        count = rg.Value
        name = rg.Offset(0, 1).Value
        Debug.Print name, count
    Next i
  
End Sub

I personally prefer the latter as it makes the code neater and it is easier to read, update and spot errors.

Using Dim in Loops

Placing a Dim statement in a Loop has no effect on the variable.

When VBA starts a Sub (or Function), the first thing it does is to create all the variables that have been declared in the Dim statements.

The following 2 pieces of code are almost the same. In the first, the variable Count is declared before the loop. In the second it is declared within the loop.

' https://excelmacromastery.com/
Sub CountOutsideLoop()

    Dim count As Long

    Dim i As Long
    For i = 1 To 3
        count = count + 1
    Next i
    
    ' count value will be 3
    Debug.Print count

End Sub
' https://excelmacromastery.com/
Sub CountInsideLoop()

    Dim i As Long
    For i = 1 To 3
        Dim count As Long
        count = count + 1
    Next i
    
    ' count value will be 3
    Debug.Print count

End Sub

The code will behave exactly the same because VBA will create the variables when it enters the sub.

Can I use Dim to Assign a Value?

In languages like C++, C# and Java, we can declare and assign variables on the same line

' C++
int i = 6
String name = "John"

We cannot do this in VBA. We can use the colon operator to place the declare and assign lines on the same line.

Dim count As Long: count = 6

We are not declaring and assigning in the same VBA line. What we are doing is placing these two lines(below) on one line in the editor. As far as VBA is concerned they are two separate lines as here:

Dim count As Long
count = 6

Here we put 3 lines of code on one editor line using the colon:

count = 1: count = 2: Set wk = ThisWorkbook

There is really no advantage or disadvantage to assigning and declaring on one editor line. It comes down to a personal preference.

Is Dim Actually Required?

The answer is that it is not required. VBA does not require you to use the Dim Statement.

However, not using the Dim statement is a poor practice and can lead to lots of problems.

You can use a variable without first using the Dim statement. In this case the variable will automatically be a variant type.

This can lead to problems such as

  1. All variables are variants (see the Variant section for issues with this).
  2. Some variable errors will go undetected.

Because of these problems it is good practice to make using Dim mandatory in our code. We do this by using the Option Explicit statement.

Option Explicit

We can make Dim mandatory in a module by typing “Option Explicit” at the top of a module.

We can make this happen automatically in each new module by selecting Tools->Options from the menu and checking the box beside “Require Variable Declaration”. Then when you insert a new module, “Option Explicit” will be automatically added to the top.

VBA Require Variable Declaration

Let’s look at some of the errors that may go undetected if we don’t use Dim.

Variable Errors

In the code below we use the Total variable without using a Dim statement

' https://excelmacromastery.com/
Sub NoDim()

    Total = 6
    
    Total = Total + 1
    
    Debug.Print Total

End Sub

If we accidentally spell Total incorrectly then VBA will consider it a new variable.

In the code below we have misspelt the variable Total as Totall:

' https://excelmacromastery.com/
Sub NoDimError()

    Total = 6
    
    ' The first Total is misspelt
    Totall = Total + 1
    
    ' This will print 6 instead of 7
    Debug.Print Total

End Sub

VBA will not detect any error in the code and an incorrect value will be printed.

Let’s add Option Explicit and try the above code again

' https://excelmacromastery.com/
Option Explicit 

Sub NoDimError()

    Total = 6
    
    ' The first Total is misspelt
    Totall = Total + 1
    
    ' This will print 6 instead of 7
    Debug.Print Total

End Sub

Now when we run the code we will get the “Variable not defined” error. To stop this error appearing we must use Dim for each variable we want to use.

When we add the Dim statement for Total and run the code we will now get an error telling us that the misspelt Totall was not defined.

variable not defined 2

This is really useful as it helps us find an error that would have otherwise gone undetected.

Keyword Misspelt Error

Here is a second example which is more subtle.

When the following code runs it should change the font in cell A1 to blue.

However, when the code runs nothing happens.

' https://excelmacromastery.com/
Sub SetColor()

    Sheet1.Range("A1").Font.Color = rgblue

End Sub

The error here is that rgblue should be rgbBlue. If you add Option Explicit to the module, the error “variable not defined” will appear. This makes solving the problem much easier.

These two examples are very simple. If you have a lot of code then errors like this can be a nightmare to track down.

Using Dim with Basic Variables

VBA has the same basic variable types that are used in the Excel Spreadsheet.

You can see a list of all the VBA variable types here.

However, most of the time you will use the following ones

Type Storage Range Description
Boolean 2 bytes True or False This variable can be either True or False.
Long 4 bytes -2,147,483,648 to 2,147,483,647 Long is short for Long Integer. Use this instead of the Integer* type.
Currency 8 bytes -1.79769313486231E308 to-4.94065645841247E-324 for negative values; 4.94065645841247E-324 to 1.79769313486232E308 for positive values Similar to Double but has only 4 decimal places
Double 8 bytes -922,337,203,685,477.5808 to 922,337,203,685,477.5807
Date 8 bytes January 1, 100 to December 31, 9999
String varies 0 to approximately 2 billion Holds text.

*Originally we would use the Long type instead of Integer because the Integer was 16-bit and so the range was -32,768 to 32,767 which is quite small for a lot of the uses of integer.

However on a 32 bit(or higher) system the Integer is automatically converted to a Long. As Windows has been 32 bit since Windows 95NT there is no point in using an Integer.

In a nutshell, always use Long for an integer type in VBA.

Fixed String Type

There is one unusual basic variable type in VBA that you may not be familiar with.

This is the fixed string type. When we create a normal string in VBA we can add text and VBA will automatically resize the string for us

' https://excelmacromastery.com/
Sub StringType()

    Dim s As String
    
    ' s is "John Smith"
    s = "John Smith"
    
    ' s is "Tom"
    s = "Tom"

End Sub

A fixed string is never resized. This string will always be the same size no matter what you assign to it

Here are some examples

' https://excelmacromastery.com/
Sub FixedString()
    
    Dim s As String * 4
    
    ' s is "John"
    s = "John Smith"
    
    ' s = "Tom "
    s = "Tom"

End Sub

Using Dim with Variants

When we declare a variable to be a variant, VBA will decide at runtime which variable type it should be.

We declare variants as follows

' Both are variants
Dim count
Dim count As Variant

This sounds like a great idea in theory. No more worrying about the variable type

' https://excelmacromastery.com/
Sub UsingVariants()
    
    Dim count As Variant
        
    count = 7
    
    count = "John"
    
    count = #12/1/2018#

End Sub

However, using variants is poor practice and this is why:

  1. Runtime Errors – VBA will not notice incorrect type errors(i.e. Data Mismatch).
  2. Compile Errors – VBA cannot detect compile errors.
  3. Intellisense is not available.
  4. Size – A variant is set to 16 bytes which is the largest variable type

Runtime Errors

Errors are your friend!

They may be annoying and frustrating when they happen but they are alerting you to future problems which may not be so easy to find.

The Type Mismatch error alerts you when incorrect data is used.

For example. Imagine we have a sheet of student marks. If someone accidentally(or deliberately) replaces a mark with text then the data is invalid.

If we use a variant to store marks then no error will occur:

' https://excelmacromastery.com/
Sub MarksVariant()
    
    Dim mark As Variant
    
    Dim i As Long
    For i = 1 To 10
        
        ' Read the mark
        mark = Sheet1.Range("A" & i).Value
        
    Next

End Sub

This is not good because there is an error with your data and you are not aware of it.

If you make the variable Long then VBA will alert you with a “Type Mismatch” error if the values are text.

' https://excelmacromastery.com/
Sub MarksLong()
    
    Dim mark As Long
    
    Dim i As Long
    For i = 1 To 10
        
        ' Read the mark
        mark = Sheet1.Range("A" & i).Value
        
    Next

End Sub

Compile Errors

Using the compiler to check for errors is very efficient. It will check all of your code for problems before you run it. You use the compiler by selecting Debug->Compile VBAProject from the menu.

In the following code, there is an error. The Square function expects a long integer but we are passing a string(i.e. the name variable):

' https://excelmacromastery.com/
Sub CompileError()

    Dim name As String

    Debug.Print Square(name)

End Sub

Function Square(value As Long) As Long
    Square = value * value
End Function

If we use Debug->Compile on this code, VBA will show us an error:

dim compile error

This is good news as we can fix this error right away. However, if we declare the value parameter as a variant:

Function Square(value As Variant) As Long
    Square = value * value
End Function

then Debug.Compile will not treat this as an error. The error is still there but it is undetected.

Accessing the Intellisense

The Intellisense is an amazing feature of VBA. It gives you the available options based on the type you have created.

Imagine you declare a worksheet variable using Dim

Dim wk As Workbook

When you use the variable wk with a decimal point, VBA will automatically display the available options for the variable.

You can see the Intellisense in the screenshot below

VBA Intellisense

If you use Variant as a type then the Intellisense will not be available

Dim wk As Variant

This is because VBA will not know the variable type until runtime.

Variant Size

The size of a variant is 16 bytes. If the variable is going to be a long then it would only take up 4 bytes. You can see that this is not very efficient.

However, unlike the 1990’s where this would be an issue, we now have computers with lots of memory and it is unlikely you will notice an inefficiency unless you are using a huge amount of variables.

Using Dim with Objects

If you don’t know what Objects are then you can read my article about VBA Objects here.

There are 3 types of objects:

  1. Excel objects
  2. Class Module objects
  3. External library objects

Note: The VBA Collection object is used in a similar way to how we use Class Module object. We use new to create it.

Let’s look at each of these in turn.

Excel objects

Excel objects such as the Workbook, Worksheet, Range, etc. do not use New because they are automatically created by Excel. See When New is not required.

When a workbook is created or opened then Excel automatically creates the associated object.

For example, in the code below we open a workbook. VBA will create the object and the Open function will return a workbook which we can store in a variable

' https://excelmacromastery.com/
Sub OpenWorkbook()
    
    Dim wk As Workbook
    Set wk = Workbooks.Open("C:Docsdata.xlsx")

End Sub

If we create a new worksheet, a similar thing happens. VBA will automatically create it and provide use access to the object.

' https://excelmacromastery.com/
Sub AddSheet()
    
    Dim sh As Worksheet
    Set sh = ThisWorkbook.Worksheets.Add

End Sub

We don’t need to use the New keyword for these Excel objects.

We just assign the variable to the function that either creates a new object or that gives us access to an existing one.

Here are some examples of assigning the Workbook, Worksheet and range variables:

' https://excelmacromastery.com/
Sub DimWorkbook()
    
    Dim wk As Workbook
    
    ' assign wk to a new workbook
    Set wk = Workbooks.Add
    
    ' assign wk to the first workbook opened
    Set wk = Workbooks(1)
    
    ' assign wk to The workbook Data.xlsx
    Set wk = Workbooks("Data.xlsx")
    
    ' assign wk to the active workbook
    Set wk = ActiveWorkbook
    
End Sub
' https://excelmacromastery.com/
Sub DimWorksheet()
    
    Dim sh As Worksheet
    
    ' Assign sh to a new worksheet
    Set sh = ThisWorkbook.Worksheets.Add
    
    ' Assign sh to the leftmost worksheet
    Set sh = ThisWorkbook.Worksheets(1)
    
    ' Assign sh to a worksheet called Customers
    Set sh = ThisWorkbook.Worksheets("Customers")
    
    ' Assign sh to the active worksheet
    Set sh = ActiveSheet

End Sub
' https://excelmacromastery.com/
Sub DimRange()

    ' Get the customer worksheet
    Dim sh As Worksheet
    Set sh = ThisWorkbook.Worksheets("Customers")
    
    ' Declare the range variable
    Dim rg As Range
    
    ' Assign rg to range A1
    Set rg = sh.Range("A1")
    
    ' Assign rg to range B4 to F10
    Set rg = sh.Range("B4:F10")
    
    ' Assign rg to range E1
    Set rg = sh.Cells(1, 5)
    
End Sub

If you want to know more about these objects you can check out these articles: VBA Workbook, VBA Worksheet and VBA Ranges and Cells.

Using Dim with Class Module Objects

In VBA we use Class Modules to create our own custom objects. You can read all about Class Modules here.

If we are creating an object then we need to use the New keyword.

We can do this in the Dim statement or in the Set statement.

The following code creates an object using the New keyword in the Dim statement:

' Declare and create
Dim o As New class1
Dim coll As New Collection

Using New in a Dim statement means that exactly one object will be created each time our code runs.

Using Set gives us more flexibility. We can create many objects from one variable. We can also create an object based on a condition.

This following code shows how we create a Class Module object using Set.

(To create a Class Module, go to the project window, right-click on the appropiate workbook and select “Insert Class Module”. See Creating a Simple Class Module for more details.)

' Declare only
Dim o As Class1

' Create using Set
Set o = New Class1

Let’s look at an example of using Set. In the code below we want to read through a range of data. We only create an object if the value is greater than 50.

We use Set to create the Class1 object. This is because the number of objects we need depends on the number of values over 50.

' https://excelmacromastery.com/
Sub UsingSet()
    
    ' Declare a Class1 object variable
    Dim o As Class1
    
    ' Read a range
    Dim i As Long
    For i = 1 To 10
        If Sheet1.Range("A" & i).Value > 50 Then

            ' Create object if condition met
            Set o = New Class1
            
        End If
    Next i

End Sub

I’ve kept this example simple for clarity. In a real-world version of this code we would fill the Class Module object with data and add it to a data structure like a Collection or Dictionary.

Here is an example of a real-world version based on the data below:

dim sample data

' Class Module - clsStudent
Public Name As String
Public Subject As String

' Standard Module
' https://excelmacromastery.com/
Sub ReadMarks()

    ' Create a collection to store the objects
    Dim coll As New Collection
    
    ' Current Region gets the adjacent data
    Dim rg As Range
    Set rg = Sheet1.Range("A1").CurrentRegion
    
    Dim i As Long, oStudent As clsStudent
    For i = 2 To rg.Rows.Count
        
        ' Check value
        If rg.Cells(i, 1).Value > 50 Then
            ' Create the new object
            Set oStudent = New clsStudent
            
            ' Read data to the student object
            oStudent.Name = rg.Cells(i, 2).Value
            oStudent.Subject = rg.Cells(i, 3).Value
            
            ' add the object to the collection
            coll.Add oStudent
            
        End If
        
    Next i
    
    ' Print the data to the Immediate Window to test it
    Dim oData As clsStudent
    For Each oData In coll
        Debug.Print oData.Name & " studies " & oData.Subject
    Next oData

End Sub

To learn more about Set you can check out here.

Objects from an External Library

A really useful thing we can do with VBA is to access external libraries. This opens up a whole new world to what we can do.

Examples are the Access, Outlook and Word libraries that allow us to communicate with these applications.

We can use libraries for different types of data structures such as the Dictionary, the Arraylist, Stack and Queue.

There are libraries for scraping a website (Microsoft HTML Object Library), using Regular Expressions (Microsoft VBScript Regular Expressions) and many other tasks.

We can create these objects in two ways:

  1. Early Binding
  2. Late Binding

Let’s look at these in turn.

Early Binding

Early binding means that we add a reference file. Once this file is added we can treat the object like a class module object.

We add a reference using Tools->Reference and then we check the appropriate file in the list.

For example, to use the Dictionary we place a check on “Microsoft Scripting Runtime”:

vba references dialog

Once we have the reference added we can use the Dictionary like a class module object

' https://excelmacromastery.com/
Sub EarlyBinding()

    ' Use Dim only
    Dim dict1 As New Dictionary
    
    ' Use Dim and Set
    Dim dict2 As Dictionary
    Set dict2 = New Dictionary

End Sub

The advantage of early binding is that we have access to the Intellisense. The disadvantage is that it may cause conflict issues on other computers.

The best thing to do is to use early binding when writing the code and then use late binding if distributing your code to other users.

Late Binding

Late binding means that we create the object at runtime.

We declare the variable as an “Object” type. Then we use CreateObject to create the object.

' https://excelmacromastery.com/
Sub LateBinding()

    Dim dict As Object
    Set dict = CreateObject("Scripting.Dictionary")
    
End Sub

Using Dim with Arrays

There are two types of arrays in VBA. They are:

  1. Static – the array size is set in the Dim statement and it cannot change.
  2. Dynamic – the array size is not set in the Dim statement. It is set later using the ReDim statement.
' STATIC ARRAY

' Stores 7 Longs - 0 to 6
Dim arrLong(0 To 6) As Long

' Stores 7 Strings - 0 to 6
Dim arrLong(6) As String

A dynamic array gives us much more flexibility. We can set the size while the code is running.

We declare a dynamic array using the Dim statement and we set the size later using ReDim.

' DYNAMIC ARRAY

' Declare the variable
Dim arrLong() As Long

' Set the size
ReDim arrLong(0 To 6) As Long

Using ReDim

The big difference between Dim and ReDim is that we can use a variable in the ReDim statement. In the Dim statement, the size must be a constant value.

' https://excelmacromastery.com/
Sub UserSet()

    ' Declare the variable
    Dim arrLong() As Long
    
    ' Ask the user for the size
    Dim size As Long
    size = InputBox("Please enter the size of the array.", Default:=1)
    
    ' Set the size based on the user input
    ReDim arrLong(0 To size) As Long

End Sub

We can actually use the Redim Statement without having first used the Dim statement.

In the first example you can see that we use Dim:

' https://excelmacromastery.com/
Sub UsingDimReDim()

    ' Using Dim
    Dim arr() As String

    ReDim arr(1 To 5) As String
    
    arr(1) = "Apple"
    arr(5) = "Orange"
    
End Sub

In the second example we don’t use Dim:

' https://excelmacromastery.com/
Sub UsingReDimOnly()

    ' Using  ReDim only
    ReDim arr(1 To 5) As String
    
    arr(1) = "Apple"
    arr(5) = "Orange"
    
End Sub

The advantage is that you don’t need the Dim statement. The disadvantage is that it may confuse someone reading your code. Either way it doesn’t make much difference.

You can use the Preserve keyword with ReDim to keep existing data while you resize an array. You can read more about this here here.

You can find everything you need to know about arrays in VBA here.

Troubleshooting Dim Errors

The table below shows the errors that you may encounter when using Dim. See VBA Errors for an explanation of the different error types.

Error Type Cause
Array already dimensioned Compile Using Redim on an array that is static
Expected: identifier Syntax Using a reserved word as the variable name
Expected: New of type name Syntax The type is missing from the Dim statement
Object variable or With block variable not set Runtime New was not used to create the object(see Creating an Object)
Object variable or With block variable not set Runtime Set was not used to assign an object variable.
User-defined type not defined Compile The type is not recognised. Can happen if a reference file is not added under Tools->Reference or the Class Module name is spelled wrong.
Statement invalid outside Type block Compile Variable name is missing from the Dim statement
Variable not defined Compile The variable is used before the Dim line.

Local versus Module versus Global Variables

When we use Dim in a procedure (i.e. a Sub or Function), it is considered to be local. This means it is only available in the procedure where it is used.

The following are the different types of variables found in VBA:

  • Local variables are variables that are available to the procedure only. Local variables are declared using the Dim keyword.
  • Module variables are variables that are only available in the current module only. Module variables are declared using the Private keyword.
  • Global variables are variables that are available to the entire project. Global variables are declared using the Public keyword.

In the code below we have declared count as a global variable:

 ' Global
 ' https://excelmacromastery.com/
 Public count As Long

 Sub UseCount1()

    count = 6
    
 End Sub

 Sub UseCount2()

    count = 4
    
 End Sub

What happens if we have a global variable and a local variable with the same name?

It doesn’t actually cause an error. VBA gives the local declaration precedence:

 ' https://excelmacromastery.com/

 ' Global
 Public count As Long 

 Sub UseCount()
    ' Local
    Dim count As Long
    
    ' Refers to the local count
    count = 6
    
 End Sub

Having a situation like this can only lead to trouble as it is difficult to track which count is being used.

In general global variables should be avoided. They make the code very difficult to read because their values can be changed anywhere in the code. This makes errors difficult to spot and resolve.

The one use of a global variable is retaining a value between code runs. This can be useful for certain applications where you want to ‘remember’ a value after the code has stopped running.

In the code below we have a sub called Update. Each time we run the Update sub(using Run->Run Sub from the menu or F5) it will add 5 to the amount variable and print the result to the Immediate Window(Ctrl + G to view this window):

 Public amount As Long

 Sub Update()
    amount = amount + 5
    Debug.Print "Update: " & amount
 End Sub

The results are:

First run: amount = 5

Second run: amount = 10

Third run: amount = 15

and so on.

If we want to clear all global variable values then we can use the End keyword. Note that the End keyword will stop the code and reset all variables so you should only use it as the last line in your code.

Here is an example of using the End keyword:

Sub ResetAllGlobals()
    End ' Resets all variables and ends the current code run
End Sub

Dim versus Private versus Public

We can declare variables using Public, Private and Dim. In some cases, they can be used interchangeably.

However, the following is the convention we use for each of the declaration keywords:

  1. Dim – used to declare local variables i.e. available only in the current procedure.
  2. Private – used to declare module variables and procedures. These are available within the current module only.
  3. Public – used to declare global variables and procedures. These are available throughout the project.
  4. Global(obsolete) – an older and obsolete version of Public. Can only be used in standard modules. It only exists for backward compatibility.

Note the Public and Private keywords are also used within Class Modules.

Conclusion

This concludes the article on the VBA Dim Statement. If you have any questions or thoughts then please let me know in the comments below.

What’s Next?

Free VBA Tutorial If you are new to VBA or you want to sharpen your existing VBA skills then why not try out the The Ultimate VBA Tutorial.

Related Training: Get full access to the Excel VBA training webinars and all the tutorials.

(NOTE: Planning to build or manage a VBA Application? Learn how to build 10 Excel VBA applications from scratch.)

Like this post? Please share to your friends:
  • Setting up forms in word
  • Setting up a word wall
  • Setting time in excel
  • Setting styles in word
  • Setting range in excel vba