What is the aspect about learning macros and Visual Basic for Applications that you find more intimidating?
For some people, the answer will revolve around having to learn a new programming language and coding. However, if you're anything like me, your answer will be the Visual Basic Editor (or VBE).
The first few times I opened the Visual Basic Editor I had no idea what I was looking at or what I was supposed to do. At the time, I really wished I had access to an Excel tutorial that explained the main features of the VBE comprehensively. Unfortunately, I didn't find it.
Obviously, in the last few years I've come a long way. Nowadays, I have no problems using the Visual Basic Editor and feel quite comfortable working on it. However, sometimes I take a look around the Internet to see if I can find a good and comprehensive Excel tutorial about the VBE. The truth is that, as of the time of this writing, there are not that many online resources covering this in detail.
I find this a little bit surprising. After all, I'm sure about one thing:
Many people who are interested in learning macros and Visual Basic for Applications feel confused the first time they open the Visual Basic Editor. I know it because, as explained above, that happened to me. This is a pity because, as explained by former Microsoft MVP and Excel guru John Walkenbach in Excel VBA Programming for Dummies:
As you become proficient with VBA, you spend lots of time working in Code windows.
The place where you'll find those Code Windows is the Visual Basic Editor. Therefore, if you want to become an advanced macro and VBA user, you must understand how to use the VBE properly.
The importance of the Visual Basic Editor and the lack of resources covering the VBE in detail are the main reasons why I decided to write this Excel tutorial. In this post, I cover the following topics:
Enough with the introduction. Let's get into the first topic of this Excel tutorial about the Visual Basic Editor.
What Is The Visual Basic Editor
The Visual Basic Editor is not exactly the same as Excel. It is actually a separate application, even though you'll usually open it through Excel. In fact, in order for the VBE to be able to run, Excel must be open.
The main function of the VBE is to allow you to write and edit VBA code.
Note that, as explained at ExcelTrick.com, the Visual Basic Editor is sometimes referred to as the Integrated Development Environment (IDE). In this Excel tutorial, I use the first term (Visual Basic Editor or VBE) but don't be confused if you see the second term being used in other places.
How To Open The Visual Basic Editor In Excel
You can open the VBE using either of the following methods:
- Click on “Visual Basic” in the Developer tab of the Ribbon.
- Use the keyboard shortcut “Alt + F11”.
How Does The Visual Basic Editor Look
The basic VBE window can be divided in the following 6 sections, all of which I explain below. In reality, there are more components than those which appear in this screenshot (such as the Locals and Watch Windows) but, since they're more advanced, I'll cover them in a future Excel tutorial.
As explained by Excel authority John Walkenbach in Excel VBA Programming for Dummies, the Visual Basic Editor:
- Has several windows.
- Is highly customizable.
As a consequence of the above, there is the possibility that your VBE window doesn't look exactly as the screenshot above.
In fact, if this is the first time that you're opening the Visual Basic Editor, you probably can't see element #6 that appears in the lower part of the image above. The reason is that this particular window (known as the Immediate Window) is, by default, hidden. I explain how you can easily unhide it below.
As you get more familiar with the VBE, you'll notice that you have a lot of flexibility regarding how the interface looks like. The Visual Basic Editor allows you to, for example:
- Hide or un-hide windows.
- Move or re-arrange windows.
- Dock windows.
Let's dive right in and understand the 6 main components of the Visual Basic Editor.
Component #1: Menu Bar
If you've been using computers for a reasonable amount of time, you're probably quite familiar with menu bars. If that's the case, the VBE menu bar is not very different from the other menu bars you've seen before.
The menu bar, basically, contains several drop-down menus. Each of the drop-down menus contains commands that you can use to interact and do things with the different components of the Visual Basic Editor.
One thing you'll notice when clicking on any menu, is that several commands have a keyboard shortcut that is displayed at that point. Take a look, for example, at the Debug menu and notice all the keyboard shortcuts that appear on the right side of this image:
Component #2: Toolbar
Again, if you're a computer user, a toolbar is an item that you've probably seen many times before. You're probably aware that a toolbar contains on-screen buttons, icons, menus and other similar elements that you can use while working with the VBE.
The toolbar that appears in the screenshot above is called the Standard toolbar. This is the only toolbar that the Visual Basic Editor displays by default. There are, however, 3 other basic toolbars:
- The Debug toolbar.
- The Edit toolbar.
- The UserForm toolbar.
In addition to the above, the VBE gives you the possibility to customize the toolbars in several ways.
You can change all of these settings by going to the View menu and selecting “Toolbars”. The Visual Basic Editor displays a menu with the 4 different toolbars and the option to access the Customize dialog.
The toolbars with a checkmark to their left are those currently displayed by Excel. You can add or remove a checkmark in order to display or hide a particular toolbar by clicking on its name. For example, in the screenshot below, only the Standard toolbar is being displayed.
If you click on “Customize”, the Visual Basic Editor displays the Customize dialog, which looks as follows:
Using this dialog box, you can control additional aspects regarding the toolbars that are displayed by the VBE. This includes, for example, the possibility of controlling the display of the Shortcut Menus toolbar or adding new toolbars.
You may be wondering what toolbar display set up is commonly applied by VBA users. In Excel VBA Programming for Dummies, Excel expert John Walkenbach explains that most people (including himself) “just leave them as they are”.
However, other Excel authorities display several toolbars. For example, Microsoft MVP Jon Peltier displays all of the standard toolbars and more. Similarly, Excel expert Dick Kusleika shows the Standard, Edit and Debug toolbars.
You can also add commonly used commands that aren't by default in the Standard toolbar.
Component #3: Project Window / Project Explorer
The Project Window, also known as the Project Explorer, is useful for navigation purposes.
This is the section of the Visual Basic Editor where you'll be able to find every single Excel workbook that is currently open. This includes add-ins and hidden workbooks. More particularly, each Excel workbook or add-in that is open at the moment appears in the Project Explorer as a separate project.
A project, as explained by Microsoft, is simply a set of modules. If it makes it easier to understand you can take John Walkenbach's explanation in Excel VBA Programming for Dummies, who says that a project can be seen as “a collection of objects arranged as an outline”.
As explained by Walkenbach in Excel 2013 Power Programming with VBA, each project may have the following nodes:
- A node called “Microsoft Excel Objects” always appears in any project. This node usually contains 2 types of objects:
#1: Each worksheet in the relevant Excel workbook. In other words, each of the worksheets is considered a separate object.
#2: The Excel workbook itself, called “ThisWorkbook”.
- The Modules node appears when the project contains VBA modules.
- If the project contains UserForm objects, which are used to create custom dialog boxes, the Project Explorer displays a node called “Forms”.
- A project can also contain class modules (modules that define a class) and, in that case, the Project Window displays a node called “Class Modules”.
- Finally, if a project has references, there is a node called “References”.
Let's take a look at how all of this looks in the VBE interface:
In the screenshot below, the only project that appears is the Excel workbook “Book 1. xlsm”. Within the Microsoft Excel Objects node, you can see that the Excel workbook has 2 worksheets. Finally, this particular project contains 1 VBA module and, therefore, the Modules node is visible. There are, however, no UserForm objects, class modules or references. Therefore, the Forms, Class Modules and References nodes don't appear.
You can expand or contract the items that appear in the outline by double-clicking on them or by clicking on the “+” or “-” that appear to the left of each item, depending on the case.
You can also control whether the items that are displayed in the Project Window appear in a hierarchical or a non-hierarchical list. You change this setting by clicking on the Toggle Folders button of the Project Window.
The screenshot above shows items being displayed in a hierarchical list. When displayed in a non-hierarchical list, the Project Window looks roughly as follows:
You can also hide or unhide the Project Explorer itself. I explain how to do this below.
How To Display The Project Window
If you can't see the Project Explorer, you can make the Visual Basic Editor display it by using any of the following methods:
- Clicking on “Project Explorer” in the View menu.
- Clicking on the Project Explorer icon in the toolbar.
- Using the keyword shortcut “Ctrl + R”.
How To Hide The Project Window
You can hide the Project Explorer by using either of the following methods:
- Clicking on the close button of the Project Window.
- Right-clicking anywhere on the Project Explorer and selecting “Hide”.
Component #4: Properties Window
The Properties Window displays the properties of the object that is currently selected in the Project Explorer and allows you to edit those properties.
Just as with the Project Window, you can hide or unhide the Properties Window. As explained at MrExcel.com, you'll need the Properties Window particularly if you start to create your own UserForms. Therefore, if you're just beginning to use the VBE, you probably won't need this window too much.
In any case, let's take a look at how you can hide or unhide the Properties Window.
How To Unhide The Properties Window
You can get the Visual Basic Editor to show the Properties Window by using any of the following methods.
- Clicking on “Properties Window” within the View menu.
- Clicking on the Properties Window icon.
- Using the “F4” keyboard shortcut.
How To Hide The Properties Window
You can get the Visual Basic Editor to hide the Properties Window by doing either of the following:
- Click on the Close button of the Properties Window.
- Right-click on the Properties Window and select “Hide”.
Component #5: Programming Window / Code Window / Module Window
As you may expect, the Code Window of the Visual Basic Editor is where your VBA code appears, and where you can write and edit such code. At the beginning, though, the Programming Window is empty as in the screenshot above.
There is a Code Window for every single object in a project. You can access the window of a particular object by going to the Project Explorer and doing any of the following:
- Double clicking on the object.
As explained in Excel 2013 VBA and Macros by Microsoft MVP Bill Jelen (Mr. Excel) and Tracy Syrstad, the exception to this rule are UserForms. If you double-click on a UserForm, the Visual Basic Editor displays the UserForm in Design view, a topic I'll cover in future tutorials.
- Selecting the object and, then, clicking on “Code” in the View menu.
- Selecting the object and clicking on the View Code icon that appears at the top of the Project Explorer.
- Right-clicking on the object and selecting “View Code”.
- Using the keyboard shortcut “F7”.
Component # 6: Immediate Window
The main purpose of the Immediate Window is to help you noticing errors, checking or debugging VBA code.
The Immediate Window is, by default, hidden. However, as with most of the other windows, you can unhide it. Let' take a look at how you can do both the hiding and the un-hiding:
How To Unhide The Immediate Window
You can unhide the Immediate Window by doing either of the following:
- Clicking on “Immediate Window” in the View menu.
- Using the “Ctrl + G” keyboard shortcut.
However, as explained in Excel VBA Programming for Dummies, if you're just getting started with the VBE “this window won't be all that useful”. Therefore, if you're just beginning to work with macros and Visual Basic for Applications, you probably don't need to display the Immediate Window.
If you're a more advanced user, you'll probably want to have the Visual Basic Editor show the Immediate Window, as Excel authority Dick Kusleika does, since this can be very useful.
How To Hide The Immediate Window
You can hide the Immediate Window using either of the following methods:
- Click the Close button.
- Right-click on the Immediate Window and select “Hide”.
You already know that:
- The VBE allows you to customize several aspects.
- On your way to becoming a macro and VBA expert you'll probably spend a significant amount of time working with the Visual Basic Editor.
Therefore, its important to have a basic idea of…
How To Customize The Visual Basic Editor
If you want to customize the Visual Basic Editor, the first thing you'll want to do is open the Options dialog. To do this, go to the Tools menu and click on “Options”.
The Options dialog looks roughly as follows.
As you can see, there are plenty of settings you can modify. In most cases, you can enable or disable an option by clicking on the blank box to the left of it. If there is a checkmark, the option is enabled. If the box is empty, the option is not enabled.
In the screenshot above, the only option that is not enabled is “Require Variable Declaration”.
For the moment, let's take a look at some of the most common suggestions made by Excel experts. The following sections go separately through each of the 4 tabs in the Options dialog:
- Editor Format.
As explained by Microsoft, the Editor tab is where you can determine the settings for the Code Window and Project Window. Let's take a look at the main settings of this tab.
Setting #1: Auto Syntax Check.
This option allows you to determine what happens when you make a syntax error while entering VBA code. There are 2 options:
- If Auto Syntax Check is enabled, a dialog box pops up as soon as the VBE discovers that you've made a syntax error. This dialog box gives you a rough idea of what mistake you've made. Additionally, the Visual Basic Editor highlights the syntax error by using a different font color (usually red).
Let's take a look at the VBA code for a very simple macro that deletes rows when some of the cells are blank. The second statement of this macro is “Selection.EntireRow.SpecialCells(xlBlanks).EntireRow.Delete”. If, for example, I press the Enter key after “Selection.”, the Visual Basic Editor gives me the following warning signs:
- If Auto Syntax Check is disabled, the Visual Basic Editor displays syntax errors in a different font color (usually red). Under this setting, no dialog boxes pop on your screen.
In the case of the syntax error used as an example above, the VBE looks roughly as follows:
Should you enable or disable the Auto Syntax Check?
This decision comes down to personal preference and knowledge of Visual Basic for Applications.
You may want to disable the Auto Syntax Check if you:
- Think that having dialog boxes popping up anytime you make a syntax error is annoying.
- Have enough knowledge of VBA in order to find out what is the problem with a statement that has a syntax error.
Some Excel authorities, such as Jon Peltier, are of the opinion that Auto Syntax Check should be disabled. Peltier's position is that “the message box is redundant” since the VBE anyway highlights the error by using red font.
However, if you're a beginner, keeping the Auto Syntax Check enabled can be of great help.
Setting #2: Require Variable Declaration.
This option allows you to determine whether the Visual Basic Editor automatically inserts a statement at the beginning of any new VBA module to require that you define (explicitly) all the variables that you use in those modules. This statement is:
Note that changing the Require Variable Declaration setting only affects future modules. Modules that are already in existence when you modify the setting are not affected.
As explained in Excel VBA Programming for Dummies, you should get used to defining explicitly all the variables that you use. In that sense, it may make sense to enable the Require Variable Declaration option. Some Excel authorities, such as Jon Peltier, say that you should enable Require Variable Declaration.
According to Peltier, one of the additional benefits of enabling this option is that it “prevents use of misspelled variable names”. The case for enabling Require Variable Declaration is even stronger if you're beginning to use the VBE. As explained by Excel expert Colin Legg at RAD Excel, this option saves you time when debugging and improves your understanding of Visual Basic for Applications.
Despite the above, some advanced Excel users (including John Walkenbach and Bill Jellen), have stated that they keep this option turned off.
Setting #3: Auto List Members.
The Auto List Members settings allows you to determine whether, while you're typing VBA code, the Visual Basic Editor displays a list of options that can be used to complete the statement you're writing. The list generally includes methods and properties that may apply to the object that you've just finished typing.
Let's see how this looks in practice by using the VBA code of the first macro that I explain in this blog post, and whose purpose is to delete an entire row if there are blank cells in specified cell range. In particular, let's take a look at the second statement, which is “Range(“E6:E257″).Select” and see what happens while I'm typing it:
The screenshot below shows how the Visual Basic Editor automatically displays a list to help me complete the statement:
If you scroll down the list, you'll notice that one of the suggestions included in that list is “Select”, which is what we're looking for.
Auto List Members has several advantages. For example, as explained in Excel 2013 Power Programming with VBA and The Spreadsheet Page:
- The Visual Basic Editor may show you properties and methods that you weren't aware of.
- The list displayed by the VBE updates itself automatically as you type characters. For example, continuing with the same example as above, the screenshot below shows the suggestions made by the Visual Basic Editor after I've partially typed “Selection”:
- You can avoid typing. This is due to the fact that you can enter any of the members that appear in the list by selecting it and pressing the Tab key or double-clicking on the relevant member.
- When you use Auto List Members, you reduce the risk of making syntax errors.
Overall, Auto List Members is probably one of the most helpful features of the Visual Basic Editor. Unless you have a very compelling reason to do otherwise, enable it.
Setting #4: Auto Quick Info.
The Auto Quick Info setting allows you to determine whether the Visual Basic Editor displays information about the arguments of functions, properties and methods as you type them.
To see how Auto Quick Info works in practice, let's go back once more over the statement “Range(“E6:E257″).Select” which I used to illustrate the Auto List Members option above. The screenshot below shows how the VBE helps me while I am typing the range:
Just as the Auto List Members setting, Auto Quick Info is a really helpful feature that you'll probably want to keep enabled.
Setting #5: Auto Data Tips.
Auto Data Tips works when you're in break mode, where program execution is temporarily suspended. This occurs for example when debugging VBA code, a topic I will cover in future tutorials.
If Auto Data Tips is enabled, and you're in break mode, the Visual Basic Editor displays the value of a variable when you place the cursor over it.
Let's take a look at Auto Data Tips in action. For these purposes, I use the VBA code for a macro that deletes an entire row when the row is completely empty. This particular macro has 2 variables: aRow and BlankRows. In the screenshot below, Excel displays the value of the variable BlankRows (BlankRows = Nothing) when I place the cursor on top of it:
This is another option that you'll probably like to enable. As explained by John Walkenbach in Excel VBA Programming for Dummies:
When you enter the wonderful world of debugging, (…) you'll appreciate this option.
Setting #6: Auto Indent.
This setting is self-explanatory. If you have Auto Indent enabled, the indentation of each line of VBA code is the same as the indentation of previous line.
In addition to the above, you can determine what is the indentation width by inputting a value in the Tab Width box. The default number of characters to indent is 4. The value you input here must be between 1 and 32.
Some Excel authorities, such as Microsoft MVP Jon Peltier, use only 2 spaces for the tab width. The reasoning behind using less indentation is that it keeps code from extending too far into the right of the screen. Other sources, such as Mastering VBA for Microsoft Office 2013, suggest that if you're not using a fixed width font (as I suggest below), it may advisable to increase this value in order to have clear levels of indentation in your Code Window.
To see how this works in practice, let's take a look at the piece of VBA code that appears in the previous example where I illustrated Auto Data Tips. The full VBA code of that macro looks as follows:
You'll notice that, near the end, there are three statements that have exactly the same indentation. The image below highlights them:
Let's assume that I am writing this piece of code and I'm about to type “BlankRows.Delete”, the second of the 3 statements I highlight in the image above:
- If Auto Indent is turned on, once I press the Enter key after “Application.ScreenUpdating = False”, the VBE takes me to a new row with exactly the same indentation. Notice the location of the cursor in the screenshot below:
- The result of pressing the Enter key is different if Auto Indent is not enabled. Check out what happens when this is the case and compare the location of the cursor between the image below and the image above:
Now, the cursor appears at the left margin of the Programming Window, regardless of the indentation of the previous row.
As explained by technical architect and software consultant Kaushik Pal at MrBool:
Indentation is one of the most important aspects in any programming domain.
So, as you may guess, you'll probably want to enable Auto Indent and set a tab width that works well for your particular circumstances and VBE settings.
Setting #1: Drag-and-Drop Text Editing.
If you enable the Drag-and-Drop Text Editing, the Visual Basic Editor allows you to move pieces of text by dragging and dropping them with your mouse.
Whether you enable this option or not depends on your own taste. I prefer to use the keyboard to copy and move pieces of VBA code. However, you may prefer to use the mouse to drag and drop.
Even if you don't plan to use it much, enabling Drag-and-Drop Text Editing doesn't do harm. Therefore, you could do the same as Excel expert John Walkenbach. In Excel VBA Programming for Dummies Walkenbach explains that he keeps the option enabled but never uses it.
Setting #2: Default to Full Module View.
This option makes reference to, and regulates, how procedures are displayed in the Programming Window.
- If Default to Full Module View is enabled, procedures generally appear as a single list in the Code Window.
Take a look, for example, at how 3 macros for deleting rows with empty cells appear in the following screenshot.
- If the option is turned off, you'll only be able to see 1 procedure at a time. You can use the Procedure Box, which is the drop-down menu at the upper right corner of the Programming Window, to switch between the different procedures.
Continuing with the example of the macros for deleting rows with empty cells, this looks roughly as follows:
You can also turn the Full Module View on and off using the Procedure View (where you can only see 1 procedure at a time) and Full Module View (where you can see all the procedures as a single list) buttons that appear on the lower left corner of the Programming Window.
This is another setting where personal taste is important. I leave Default to Full Module View enabled and my guess is that most Excel users would prefer to do the same.
Setting #3: Procedure Separator.
This setting is kind of self-explanatory. If enabled, it separates the procedures in the Code Window with a bar. This looks roughly as follows:
Without procedure separators, the Code Window (with the same macros that appear above) looks roughly as follows:
You'd probably agree that the first screen is more organized and makes it easier to distinguish between the different procedures. If that's the case, you'd prefer to enable Procedure Separators.
In certain cases, there may be reasons to disable Procedure Separators but this is not that common.
One case where it makes sense to disable this option is provided at peltiertech.com. In this website, Jon Peltier explains how he uses a particular routine to print out code by extracting it first to Microsoft Word. Since the procedure separators aren't exported into Word, Peltier uses simple lines as separators. This case is a very specific situation though.
Editor Format Tab
As implied by its name, the Editor Format tab is where you can format the editor. In other words, here is where you can customize the way the VBA code looks.
On the right side of the Options dialog, you'll notice that there is a Sample box. Here is where the VBE provides you an example of how the text in the Visual Basic Editor looks under the current settings. For example:
The Editor Format regulates the way the Visual Basic Editor looks using 4 sections. Let's take a look at each of them.
Section #1: Code Colors.
The Code Colors settings allows you to determine 3 characteristics for any type of text: font color, highlighting color and margin indicator. You can adjust these settings in 2 simple steps.
Step #1: Determine The Category Of Text You Want To Configure.
You can select which type of text you want to adjust by selecting it in the first list that appears on the upper left corner of the Options dialog.
Step #2: Adjust The Foreground, Background and Indicator Settings.
Once you've selected the type of text whose settings you want to modify, you can proceed to set the following 3 characteristics by using the relevant drop-down menus:
- The font color, determined by “Foreground” in the Options dialog.
- The highlighting color, set by “Background”.
- Whether the Visual Basic Editor displays an indicator on the margin of the Programming Window, and the color of that indicator.
In order to understand how this looks in practice, let's take a look at the default settings for 2 types of text.
- As you've seen above (when reading about the Auto Syntax Check option), the Visual Basic Editor highlights syntax errors by making their font color red (by default).
The following screenshot shows the configuration for this type of text in the Options dialog:
- One of the screenshots I use above (when explaining Auto Data Tips) shows text highlighted in yellow. This is known as Execution Point Text and its configuration looks as follows:
Code Color settings are, as many other of these settings, a matter of personal taste. I prefer to leave the default colors. However, you may want to play around with the settings to find the configuration you like the most.
Section #2: Font.
As you probably expect, Font settings allow you to determine which font is used to display the VBA code in the Programming Window.
The default font is Courier New and my suggestion is that you keep it. The reason for this is that this font is fixed-width. In fixed-width fonts, all of the characters are the same width and, therefore, use up the same amount of horizontal space. As explained by John Walkenbach:
This makes your code more readable because the characters are nicely aligned vertically, and you can easily distinguish multiple spaces (which is sometimes useful).
Section #3: Size.
This is another setting that is self-explanatory. Here is where you can specify the font size used in the Code Window. This setting is a matter of personal taste, although factors such as the monitor you're using may affect your decision.
Section #4: Margin Indicator Bar.
You can use this setting to determine whether to turn on or off the margin indicator bar.
So, what is the margin indicator bar?
This is the grey bar that appears on the left side of the Programming Window of the VBE. It displays very useful indicators that'll help you, for example, when debugging your VBA code.
In the last screenshot above, I showed you the Code Colors settings for Execution Point Text. Now, let's take a look at how Execution Point Text appears in the Code Window. Notice the indicator for this text in the margin indicator bar.
This is one of the settings that you'll want to turn on. As mentioned above, margin indicators can be very useful when working on the Visual Basic Editor.
The General tab of the Options dialog contains settings that fall in a variety of categories such as form, error handling and compiling. Additionally, several of them are relevant only for more advanced topics, such as debugging. Therefore, I only provide a rough explanation of the different options that are available in this tab.
In any case, as suggested by John Walkenbach in Excel VBA Programming for Dummies, when you're starting to work with the VBE, the default settings in this particular tab should work well enough.
Setting #1: Form Grid Settings.
In Mastering VBA for Microsoft Office 2013, author Richard Mansfield explains that the Form Grid Settings allow you to control the way in which the VBE handles UserForms.
This is a more advanced topic that I'll cover in future tutorials. Please feel free to enter your email address below to be notified as soon as I publish new posts in Power Spreadsheets.
Setting #2: Show ToolTips.
ToolTips are descriptions that the Visual Basic Editor can display in order to help you understand a particular toolbar button. If Show ToolTips is enabled, ToolTips are displayed automatically whenever you hover over a particular button.
As an example, the following image shows the ToolTip for the Project Explorer button in the VBE Standard toolbar:
Having ToolTips enabled is generally considered useful.
Setting #3: Collapse Proj. Hides Windows.
This option does what its title says: when you collapse a project in the Project Explorer, it hides any window related to that particular project. As explained by Microsoft here, this applies to project, UserForm, object or module windows.
Let's take a look at how this looks in practice. Notice how, in the following image, the project “Book 1.xlsm” is expanded and you can see the Programming Window that corresponds to Module1.
Compare the above with the next screenshot. In this image, I have simply collapsed the project in the Project Window. As a result, all related windows (the most prominent being the Code Window) are hidden.
As explained in Mastering VBA for Office 2013, if you expand the project again, the windows that have been hidden are restored in their previous positions.
Enabling Collapse Proj. Hides Windows is, usually, a good idea.
Setting #4: Edit and Continue & Notify Before State Loss.
When the Notify Before State Loss setting is enabled, the VBE issues you a notification if the following conditions are met:
- You're running VBA code.
- You attempt to do something that requires the resetting of all the variables in the module.
Setting #5: Error Trapping.
As implied by its name, error trapping makes reference to how errors are trapped and handled when the VBA code runs.
Let's take a quick look at what each of the 3 available options does:
- If you choose “Break on All Errors”, break mode is entered whenever there is an error in the VBA code. This includes cases where there may be an error handler or the code is in a class module.
This option may be useful when doing debugging. However, at the beginning, I suggest that you don't choose it.
- When “Break in Class Module” is enabled, break mode is entered if there is an error in the VBA code within a class module.
This is the setting suggested by, among others experts, Richard Mansfield in Mastering VBA for Microsoft Office 2013 and Colin Legg.
- “Break on Unhandled Errors” is the default setting. This is also the choice suggested by Excel guru John Walkenbach in Excel VBA Programming for Dummies.
Under this setting, break mode won't be entered as long as there is an error handler that traps the error. However, if there is no adequate error handler, break mode is entered.
Setting #6: Compile.
The Compile settings allow you to control the moment at which VBA code is compiled.
Why is this important?
At this moment is not necessary to go too deep into the concept of compiling. For the moment, is enough to understand that applications written in a particular programming language (which can't be executed by a computer) need to be transformed into another language (that can be executed by the computer). As explained in Mastering VBA for Microsoft Office 2013:
Before any code can be executed, it needs to be compiled, but not all code in a project must necessarily be compiled before the Visual Basic Editor can start executing the first parts of the code.
With this in mind, let's take a look at the 2 options that appear in the General tab.
Option #1: Compile On Demand.
Compile On Demand means that the Visual Basic Editor compiles the VBA code as is needed. Let's take a look at an example to understand how Compile On Demand works:
Let's assume, for example, that you're working with 5 procedures named “Procedure1” through “Procedure5”. You want to first run Procedure1. Procedure1 calls Procedure2 which, in turn, calls Procedure3. Procedure3 doesn't call any further procedures.
If Compile On Demand is enabled, Procedure1 is the only procedure that is compiled at the beginning of the process described above. No additional code (from the other procedures) is compiled until the relevant procedure is called. Once Procedure1 calls Procedure2, the code of Procedure2 is compiled. Similarly, once Procedure2 calls Procedure 3, Procedure3 is compiled. Since Procedure4 and Procedure5 aren't called, their codes are not compiled.
If Compile On Demand is disabled, the code of all the procedures (Procedure1 through Procedure5) is compiled before Procedure1 starts running. As you can imagine, under this scenario, the procedure you want to execute starts running a little bit later since there is more code to be compiled. Additionally, as explained by Richard Mansfield in Mastering VBA for Microsoft Office 2013, you wont be able to run the procedure you want (Procedure1) if there is any language or compile error in any of the other procedures (Procedure2 to Procedure5).
Option #2: Background Compile.
This option is only available if you have enabled Compile On Demand. As implied by its name, Background Compile means that idle time is used for purposes of finish compiling a program in the background.
The Docking tab is used to set the behavior of the different windows of the Visual Basic Editor. More precisely, is used to determine whether a tab docks, a concept that I explain below.
A window is dockable if the box to its left has a checkmark. Otherwise, the window isn't dockable. In the screenshot below, the only window that isn't dockable is the Object Browser.
You may be wondering what exactly happens when a window is dockable. The difference between being dockable and not is the following:
- When a window is docked, the VBE fixes that window in a certain spot along one of the edges of the Visual Basic Editor window.
Check out, for example, how the Project Explorer and Properties Window are are fixed along the left edge of the VBE window:
- If windows are not docked, you just have a bunch of windows within the VBE.
Compare the screenshot above with the following image, where the Project and Properties Windows are not docked. This image is only for illustration purposes. You can maximize and minimize these windows by clicking on the relevant buttons at the top right hand of the relevant window.
As you probably expect, I suggest that you dock most windows. Having the different VBE windows docked makes it easier to locate the window that you need when you need it, and generally improves the user experience.
If your screen is not big enough to dock the windows along the edges of the VBE, you may want to undock some of them. If you do this, you'll probably have to switch between windows in order to get to the one you want. The advantage of having few (or none) docked windows is that you'll have more space for your Code Window.
How To Add VBA Modules
When you record a macro, Excel automatically inserts a module into the Excel workbook you choose before beginning to record. However, there are other opportunities where you may want to add other VBA modules. You can do this by using either of the following methods.
How To Add A VBA Module: Method #1
Under this method, you can add a VBA module to a project in 2 easy steps.
Step #1: Select Project To Add Module To.
Go to the Project Explorer and select the project to which you want to add a module. For example, in the screenshot below, a module would be added to “VBAProject (Book 1.xlsm)”, which is the only open project.
Step #2: Insert Module.
Go to the Insert menu and select “Module”.
How To Add A VBE Module: Method #2
In this case, you add a module by right-clicking on the relevant project (in the Project Window), choosing “Insert” and clicking on “Module”.
How To Remove VBA Modules
Just as you can add new VBA modules to a project, you can remove them by using either of the following 2 methods.
Note that, as explained by John Walkenbach in Excel VBA Programming for Dummies, you can only remove VBA modules. In Walkenbach's words:
There is not way to remove the other code modules – those for the Sheet objects or ThisWorkbook.
How To Remove A VBA Module: Method #1
In this method, you can remove a VBA module by following 2 simple steps.
Step #1: Select Module To Be Removed.
Go to the Project Window and select the relevant module. For example, if you wanted to remove “Module2”.
Step #2: Remove Module.
Go to the File menu and select “Remove module_name”, where “module_name” stands for the name of the module you want to remove. For example, when removing “Module2”, the File menu looks roughly as follows:
How To Remove A VBA Module: Method #2
Under this method, you simply right-click on the relevant module in the Project Explorer and select “Remove module_name”. For example, in the case of “Module2”:
Regardless of which of the 2 methods above you use to remove a VBA module, the Visual Basic Editor displays a dialog asking you whether you want to export the module before actually removing it.
Most of the times, the reason why you're removing a VBA module is because you don't need the VBA code within it. In those cases, click “No”.
If, for any reason, you actually want to export the module, click on “Yes”. However, if you are interested in learning how to export objects in the Visual Basic Editor, take a look at the next section of this Excel tutorial…
How To Export Or Import An Object In The Visual Basic Editor
Let's assume that you're working on a VBA project and want to be able to access a particular object separately and use it, for example, in future VBA projects or share it with your colleagues. To do this, you need to learn how to export and import objects in the VBE.
But first, let's define exporting and importing:
- Exporting an object means taking a particular VBA object from a VBA project and saving it in a separate file. Graphically, this looks as follows:
- Importing is, basically, the opposite of exporting. More precisely, it means taking a VBA object from a separate file and into a particular VBA project. Graphically:
As explained in Excel 2013 Power Programming with VBA, you can't export the objects that appear under the References node in the Project Explorer.
Also, if you export a UserForm object, the code associated with that UserForm is also exported. Therefore, exporting a UserForm actually creates 2 separate files.
Now, let's take a look at how to export an object in the Visual Basic Editor…
How To Export An Object In The Visual Basic Editor
First of all, if your purpose for exporting an object is to use it another project, you may not need to go through the whole exporting and importing process. As suggested by John Walkenbach in Excel 2013 Power Programming with VBA, you can simply proceed as follows to achieve the result of having the object in both projects:
- Open both the original and the destination projects.
- Use the mouse to drag the relevant object from the original project to the destination project.
If you still need to export an object using the Visual Basic Editor, simply follow these 3 easy steps.
Step #1: Select The Object You Want To Export.
Go to the Project Window and click on the VBA object you want to export. For example, if you want to export Module2:
Step #2: Instruct The VBE To Export The Object.
You can instruct the Visual Basic Editor to export the object by using either of the following methods:
- Clicking on “Export File…” in the File menu:
- Right-clicking on the object you want to export and selecting “Export File…”.
- Using the “Ctrl + E” keyboard shortcut.
Step #3: Save The File.
Once you've instructed the VBE to export the object, the Export File dialog appears.
This dialog probably looks quite familiar. Here you get to save the exported object as any other file. Basically, choose the folder you want to save the file in (in the screenshot below is “Example”), give the file a name (in the image below is “Module2”) and click “Save”.
Note that, as explained in Excel VBA Programming for Dummies, the type of file that is saved depends on the type of object that you're actually exporting. In all of the cases, however, the result is a text file.
You don't need to worry about this too much, as the Visual Basic Editor tells you automatically what is the type of the file to be saved. In the example above, Module2 is a Basic File (*.bas).
Once you've completed the 3 steps above, the object is saved in a separate file. You can now, among others, share the exported object with your colleagues or use it yourself in other VBA projects.
This exported file is only a copy of the original VBA object. Therefore, the Visual Basic Editor keeps the original object in the project and you can continue working with it as usual.
How To Import An Object In The Visual Basic Editor
You can import an object in the Visual Basic Editor in 3 simple steps.
Step #1: Select The Project.
Go to the Project Window and select the project into which you want to import the object.
For example, if you want to import the object into the Excel workbook named “Book 1.xlsm”:
Step #2: Instruct The VBE To Import An Object.
You can give the Visual Basic Editor the instruction to import an object in any of the following 3 ways:
- Go to the File menu and click on “Import File…”.
- Right-click on the project and select “Import File…”.
- Use the “Ctrl + M” keyboard shortcut.
Step #3: Select The File To Be Imported.
After you've instructed the Visual Basic Editor to import a file, the Import File dialog is displayed.
You've probably seen very similar dialog boxes before and, therefore, are probably quite familiar with them. Here, you just need to:
- Find the file that you want to import.
- Select the file and click on the Open button on the lower right corner of the screen, or simply double click on the file name.
For example, if you wanted to import the module that was exported in the example above and which is named “Module2”:
If you plan on becoming an expert on macros and Visual Basic for Applications, you'll have to understand and master working with the Visual Basic Editor. Even though the VBE may look intimidating at first, you now know enough about it to start using it appropriately and start creating macros now.
Since this tutorial is aimed at VBA beginners, I haven't covered a few advanced topics. If you want to be informed about future tutorials, including those that cover more advanced VBE matters, please enter your email below.
Books Referenced In This Excel Tutorial
Click on any of the images below to purchase the book at Amazon now. PowerSpreadsheets.com is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to Amazon.com.