The first step to working with VBA in Excel is to get yourself familiarized with the Visual Basic Editor (also called the VBA Editor or VB Editor).
In this tutorial, I will cover all there is to know about the VBA Editor and some useful options that you should know when coding in Excel VBA.
What is Visual Basic Editor in Excel?
Visual Basic Editor is a separate application that is a part of Excel and opens whenever you open an Excel workbook. By default, it’s hidden and to access it, you need to activate it.
VB Editor is the place where you keep the VB code.
There are multiple ways you get the code in the VB Editor:
- When you record a macro, it automatically creates a new module in the VB Editor and inserts the code in that module.
- You can manually type VB code in the VB editor.
- You can copy a code from some other workbook or from the internet and paste it in the VB Editor.
Opening the VB Editor
There are various ways to open the Visual Basic Editor in Excel:
- Using a Keyboard Shortcut (easiest and fastest)
- Using the Developer Tab.
- Using the Worksheet Tabs.
Let’s go through each of these quickly.
Keyboard Shortcut to Open the Visual Basic Editor
The easiest way to open the Visual Basic editor is to use the keyboard shortcut – ALT + F11 (hold the ALT key and press the F11 key).
As soon as you do this, it will open a separate window for the Visual Basic editor.
This shortcut works as a toggle, so when you use it again, it will take you back to the Excel application (without closing the VB Editor).
The shortcut for the Mac version is Opt + F11 or Fn + Opt + F11
Using the Developer Tab
To open the Visual Basic Editor from the ribbon:
- Click the Developer tab (if you don’t see a developer tab, read this on how to get it).
- In the Code group, click on Visual Basic.
Using the Worksheet Tab
This is a less used method to open the Vb Editor.
Go to any of the worksheet tabs, right-click, and select ‘View Code’.
This method wouldn’t just open the VB Editor, it will also take you to the code window for that worksheet object.
This is useful when you want to write code that works only for a specific worksheet. This is usually the case with worksheet events.
Anatomy of the Visual Basic Editor in Excel
When you open the VB Editor for the first time, it may look a bit overwhelming.
There are different options and sections that may seem completely new at first.
Also, it still has an old Excel 97 days look. While Excel has improved tremendously in design and usability over the years, the VB Editor has not seen any change in the way it looks.
In this section, I will take you through the different parts of the Visual Basic Editor application.
Note: When I started using VBA years ago, I was quite overwhelmed with all these new options and windows. But as you get used to working with VBA, you would get comfortable with most of these. And most of the time, you’ll not be required to use all the options, only a hand full.
Below is an image of the different components of the VB Editor. These are then described in detail in the below sections of this tutorial.
Now let’s quickly go through each of these components and understand what it does:
Menu Bar
This is where you have all the options that you can use in the VB Editor. It is similar to the Excel ribbon where you have tabs and options with each tab.
You can explore the available options by clicking on each of the menu element.
You will notice that most of the options in VB Editor have keyboard shortcuts mentioned next to it. Once you get used to a few keyboard shortcuts, working with the VB Editor becomes really easy.
Tool Bar
By default, there is a toolbar in the VB Editor which has some useful options that you’re likely to need most often. This is just like the Quick Access Toolbar in Excel. It gives you quick access to some of the useful options.
You can customize it a little by removing or adding options to it (by clicking on the small downward pointing arrow at the end of the toolbar).
In most cases, the default toolbar is all you need when working with the VB Editor.
You can move the toolbar above the menu bar by clicking on the three gray dots (at the beginning of the toolbar) and dragging it above the menu bar.
Note: There are four toolbars in the VB Editor – Standard, Debug, Edit, and User form. What you see in the image above (which is also the default) is the standard toolbar. You can access other toolbars by going to the View option and hovering the cursor on the Toolbars option. You can add one or more toolbars to the VB Editor if you want.
Project Explorer
Project Explorer is a window on the left that shows all the objects currently open in Excel.
When you’re working with Excel, every workbook or add-in that is open is a project. And each of these projects can have a collection of objects in it.
For example, in the below image, the Project Explorer shows the two workbooks that are open (Book1 and Book2) and the objects in each workbook (worksheets, ThisWorkbook, and Module in Book1).
There is a plus icon to the left of objects that you can use to collapse the list of objects or expand and see the complete list of objects.
The following objects can be a part of the Project Explorer:
- All open Workbooks – within each workbook (which is also called a project), you can have the following objects:
- Worksheet object for each worksheet in the workbook
- ThisWorkbook object which represents the workbook itself
- Chartsheet object for each chart sheet (these are not as common as worksheets)
- Modules – This is where the code that is generated with a macro recorder goes. You can also write or copy-paste VBA code here.
- All open Add-ins
Consider the Project Explorer as a place that outlines all the objects open in Excel at the given time.
The keyboard shortcut to open the Project Explorer is Control + R (hold the control key and then press R). To close it, simply click the close icon at the top right of the Project Explorer window.
Note: For every object in Project Explorer, there is a code window in which you can write the code (or copy and paste it from somewhere). The code window appears when you double click on the object.
Properties Window
Properties window is where you get to see the properties of the select object. If you don’t have the Properties window already, you can get it by using the keyboard shortcut F4 (or go to the View tab and click Properties window).
Properties window is a floating window which you can dock in the VB Editor. In the below example, I have docked it just below the Project Explorer.
Properties window allows us to change the properties of a selected object. For example, if I want to make a worksheet hidden (or very hidden), I can do that by changing the Visible Property of the selected worksheet object.
Related: Hiding a Worksheet in Excel (that can not be un-hidden easily)
Code Window
There is a code window for each object that is listed in the Project Explorer. You can open the code window for an object by double-clicking on it in the Project Explorer area.
Code window is where you’ll write your code or copy paste a code from somewhere else.
When you record a macro, the code for it goes into the code window of a module. Excel automatically inserts a module to place the code in it when recording a macro.
Related: How to Run a Macro (VBA Code) in Excel.
Immediate Window
The Immediate window is mostly used when debugging code. One way I use the Immediate window is by using a Print.Debug statement within the code and then run the code.
It helps me to debug the code and determine where my code gets stuck. If I get the result of Print.Debug in the immediate window, I know the code worked at least till that line.
If you’re new to VBA coding, it may take you some time to be able to use the immediate window for debugging.
By default, the immediate window is not visible in the VB Editor. You can get it by using the keyboard shortcut Control + G (or can go to the View tab and click on ‘Immediate Window’).
Where to Add Code in the VB Editor
I hope you now have a basic understanding of what VB Editor is and what all parts it has.
In this section of this tutorial, I will show you where to add a VBA code in the Visual Basic Editor.
There are two places where you can add the VBA code in Excel:
- The code window for an object. These objects can be a workbook, worksheet, User Form, etc.
- The code window of a module.
Module Code Window Vs Object Code Window
Let me first quickly clear the difference between adding a code in a module vs adding a code in an object code window.
When you add a code to any of the objects, it’s dependent on some action of that object that will trigger that code. For example, if you want to unhide all the worksheets in a workbook as soon as you open that workbook, then the code would go in the ThisWorkbook object (which represents the workbook).
The trigger, in this case, is opening the workbook.
Similarly, if you want to protect a worksheet as soon as some other worksheet is activated, the code for that would go in the worksheet code window.
These triggers are called events and you can associate a code to be executed when an event occurs.
Related: Learn more about Events in VBA.
On the contrary, the code in the module needs to be executed either manually (or it can be called from other subroutines as well).
When you record a macro, Excel automatically creates a module and inserts the recorded macro code in it. Now if you have to run this code, you need to manually execute the macro.
Adding VBA Code in Module
While recording a macro automatically creates a module and inserts the code in it, there are some limitations when using a macro recorder. For example, it can not use loops or If Then Else conditions.
In such cases, it’s better to either copy and paste the code manually or write the code yourself.
A module can be used to hold the following types of VBA codes:
- Declarations: You can declare variables in a module. Declaring variables allows you to specify what type of data a variable can hold. You can declare a variable for a sub-routine only or for all sub-routines in the module (or all modules)
- Subroutines (Procedures): This is the code that has the steps you want VBA to perform.
- Function Procedures: This is a code that returns a single value and you can use it to create custom functions (also called User Defined Functions or UDFs in VBA)
By default, a module is not a part of the workbook. You need to insert it first before using it.
Adding a Module in the VB Editor
Below are the steps to add a module:
- Right-click on any object of the workbook (in which you want the module).
- Hover the cursor on the Insert option.
- Click on Module.
This would instantly create a folder called Module and insert an object called Module 1. If you already have a module inserted, the above steps would insert another module.
Once the module is inserted, you can double click on the module object in the Project Explorer and it will open the code window for it.
Now you can copy-paste the code or write it yourself.
Removing the Module
Below are the steps to remove a module in Excel VBA:
- Right-click on the module that you want to remove.
- Click on Remove Module option.
- In the dialog box that opens, click on No.
Note: You can export a module before removing it. It gets saved as a .bas file and you can import it in some other project. To export a module, right-click on the module and click on ‘Export file’.
Adding Code to the Object Code Window
To open the code window for an object, simply double-click on it.
When it opens, you can enter the code manually or copy-paste the code from other modules or from the internet.
Note that some of the objects allow you to choose the event for which you want to write the code.
For example, if you want to write a code for something to happen when selection is changed in the worksheet, you need to first select worksheets from the drop-down at the top left of the code window and then select the change event from the drop-down on the right.
Note: These events are specific to the object. When you open the code window for a workbook, you will see the events related to the workbook object. When you open the code window for a worksheet, you will see the events related to the worksheet object.
Customizing the VB Editor
While the default settings of the Visual Basic Editor are good enough for most users, it does allow you to further customize the interface and a few functionalities.
In this section of the tutorial, I will show you all the options you have when customizing the VB Editor.
To customize the VB Editor environment, click Tools in the menu bar and then click on Options.
This would open the Options dialog box which will give you all the customization options in the VB Editor. The ‘Options’ dialog box has four tabs (as shown below) that have various customizations options for the Visual Basic Editor.
Let’s quickly go through each of these tabs and the important options in each.
Editor Tab
While the inbuilt settings work fine in most cases, let me still go through the options in this tab.
As you get more proficient working with VBA in Excel, you may want to customize the VB Editor using some of these options.
Auto Syntax Check
When working with VBA in Excel, as soon as you make a syntax error, you will be greeted by a pop-up dialog box (with some description about the error). Something as shown below:
If you disable this option, this pop-up box will not appear even when you make a syntax error. However, there would be a change in color in the code text to indicate that there is an error.
If you’re a beginner, I recommend you keep this option enabled. As you get more experienced with coding, you may start finding these pop-up boxes irritating, and then you can disable this option.
Require Variable Declaration
This is one option I recommend enabling.
When you’re working with VBA, you would be using variables to hold different data types and objects.
When you enable this option, it automatically inserts the ‘Option Explicit’ statement at the top of the code window. This forces you to declare all the variables that you’re using in your code. If you don’t declare a variable and try to execute the code, it will show an error (as shown below).
In the above case, I used the variable Var, but I didn’t declare it. So when I try to run the code, it shows an error.
This option is quite useful when you have a lot of variables. It often helps me find misspelled variables names as they are considered as undeclared and an error is shown.
Note: When you enable this option, it does not impact the existing modules.
Auto List Member
This option is quite useful as it helps you get a list of properties of methods for an object.
For example, if I want to delete a worksheet (Sheet1), I need to use the line Sheet1.Delete.
While I am typing the code, as soon as I type the dot, it will show me all the methods and properties associated with the Worksheet object (as shown below).
Auto list feature is great as it allows you to:
- Quickly select the property and method from the list and saves time
- Shows you all the properties and methods which you may not be aware of
- Avoid making spelling errors
This option is enabled by default and I recommend keeping it that way.
Auto Quick Info Options
When you type a function in Excel worksheet, it shows you some information about the function – such as the arguments it takes.
Similarly, when you type a function in VBA, it shows you some information (as shown below). But for that to happen, you need to make sure the Auto Quick Info option is enabled (which it is by default).
Auto Data Tips Options
When you’re going through your code line by line and place your cursor above a variable name, it will show you the value of the variable.
I find it quite useful when debugging the code or going through the code line by line which has loops in it.
In the above example, as soon as I put the cursor over the variable (var), it shows the value it holds.
This option is enabled by default and I recommend you keep it that way.
Auto Indent
Since VBA codes can get long and messy, using indentation increases the readability of the code.
When writing code, you can indent using the tab key.
This option ensures that when you are done with the indented line and hit enter, the next line doesn’t start from the very beginning, but has the same indentation as the previous line.
In the above example, after I write the Debug.Print line and hit enter, it will start right below it (with the same indentation level).
I find this option useful and turning this off would mean manually indenting each line in a block of code that I want indented.
You can change the indentation value if you want. I keep it at the default value.
Drag and Drop Text Editing
When this option is enabled, it allows you to select a block of code and drag and drop it.
It saves time as you don’t have to first cut and then paste it. You can simply select and drag it.
This option is enabled by default and I recommend you keep it that way.
Default to Full Module View
When this option is enabled, you will be able to see all the procedures in a module in one single scrollable list.
If you disable this option, you will only be able to see one module at a time. You will have to make a selection of the module you want to see from the drop-down at the top right of the code window.
This option is enabled by default and I recommend keeping it that way.
One reason you may want to disable it when you have multiple procedures that are huge and scrolling across these is taking time, or when you have a lot of procedures and you want to quickly find it instead of wasting time in scrolling.
Procedure Separator
When this option is enabled, you will see a line (a kind of divider) between two procedures.
I find this useful as it visually shows when one procedure ends and the other one starts.
It’s enabled by default and I recommend keeping it that way.
Editor Format Tab
With the options in the Editor Format tab, you can customize the way your code looks in the code window.
Personally, I keep all the default options as I am fine with it. If you want, you can tweak this based on your preference.
To make a change, you need to first select an option in the Code Colors box. Once an option is selected, you can modify the foreground, background, and indicator color for it.
The font type and font size can also be set in this tab. It’s recommended to use a fixed-width font such as Courier New, as it makes the code more readable.
Note that the font type and size setting will remain the same for all code types (i.e., all the code types shown in the code color box).
Below is an image where I have selected Breakpoint, and I can change the formatting of it.
Note: The Margin Indicator Bar option when enabled shows a little margin bar to the left of the code. It’s helpful as it shows useful indicators when executing the code. In the above example, when you set a breakpoint, it will automatically show a red dot to the left of the line in the margin bar. Alternatively, to set a breakpoint, you can simply click on the margin bar on the left of the code line that you want as the breakpoint.
By default, Margin Indicator Bar is enabled and I recommend keeping it that way.
One of my VBA course students found this customization options useful and she was color blind. Using the options here, she was able to set the color and formats that made it easy for her to work with VBA.
General Tab
The General tab has many options but you don’t need to change any of it.
I recommend you keep all the options as is.
One important option to know about in this tab is Error Handling.
By default, ‘Break on Unhandled Errors’ is selected and I recommend keeping it that way.
This option means that if your code encounters an error, and you have not handled that error in your code already, then it will break and stop. But if you have addressed the error (such as by using On Error Resume Next or On Error Goto options), then it will not break (as the errors are not unhandled).
Docking Tab
In this tab, you can specify which windows you want to get docked.
Docking means that you can fix the position of a window (such as project explorer or the Properties window) so that it doesn’t float around and you can view all the different windows at the same time.
If you don’t dock, you will be able to view one window at a time in full-screen mode and will have to switch to the other one.
I recommend keeping the default settings.
Other Excel tutorials you may like:
- How to Remove Macros From an Excel Workbook
- Comments in Excel VBA (Add, Remove, Block Commenting)
- Using Active Cell in VBA in Excel (Examples)
In this Article
- Opening the Visual Basic Editor
- To enable the Developer Ribbon
- Understanding the VBE Screen
- Inserting a module or form into your code
- Removing a Module or Form from the Project Explorer
- The Properties Window
- The Code Window
- Understanding the Code
- Sub Procedures
- Function Procedures
- Creating a new Procedure
- Writing Code that is easy to understand and navigate
- Adding Comments
- Indenting
- UpperCase vs LowerCase
- AutoComplete
- Error trapping and Debugging
- Syntax errors
- Compilation Errors
- Runtime Errors
- Logical Errors
- On Error Go To
- On Error Resume Next
This tutorial will show you how to open and program in the Visual Basic Editor in VBA.
Opening the Visual Basic Editor
There are a few ways to access the Visual Basic Editor (VBE) in Excel.
Press Alt + F11 on your keyboard.
OR
Click View > Macros > View Macros. From here you can Edit an existing macro or Create a new one. Either option opens up the VB Editor.
OR
Developer > Visual Basic
Note: If you don’t see the Developer Ribbon, you’ll need to enable it.
To enable the Developer Ribbon
Click on the File tab in the Ribbon, and go down to Options. In the Customize Ribbon options, tick the Developer check box. This is switched off by default so you will need to switch it on to see the tab on the ribbon.
Click OK.
The Developer tab will appear on the main ribbon. Click on Visual Basic at the start of the ribbon to access the Visual Basic Editor.
Understanding the VBE Screen
The VBE Screen is shown in the graphic below.
The Project Explorer
The Project Explorer enables you to see how the Project in which you are working is organized. You can see how many modules and forms are stored in the project, and can navigate between these modules and forms. A module is where the code in your workbook is stored, when you record a macro, it will be stored in a standard module – which will by default be named ‘Module1’.
Each of the worksheets in your Excel file also has module behind it, as does the workbook itself. When you insert a new sheet into the workbook via the main Excel screen, you will see an additional sheet module appear in the Project Explorer.
Double-click on a module to move to the code for that module.
You can also click on the Window menu on the toolbar and select the module there to move to the code for that module.
Type of Modules
The modules are organized into 5 different types.
- Standard modules – most of your code will go into this type of module. When you record a macro, it gets put into a standard module. When you write a general procedure to be used throughout your workbook, it also normally goes into a standard module.
- Workbook modules – this module holds the code the is unique to that individual workbook. Most of the code in these type of modules are known as EVENTS. An event can occur when a workbook is opened or closed for example. The module can also contain code that is written by yourself and used by the events.
- Sheet modules – this module holds the code that is unique to that individual sheet. They can occur when a sheet is clicked on for example (the Click Event), or when you change data in a cell. This module can also hold code that is written by yourself and called by the Events.
- Form modules – this is the module behind a custom form that you may create. For example you may create a form to hold details for an invoice, with an OK button, the code behind the button (the Click Event) contains the code that will run when the button is clicked.
- Class modules – this module is used to create objects at run time. Class module are used by Advanced VBA programmers and will be covered at a later stage.
Inserting a module or form into your code
To insert a new module into your code, click on the Insert option on the menu bar, and click Module.
Or, click on the Insert Module button which you will find on the standard ribbon.
To insert a new user form into your code, select the UserForm option.
A new user form will appear in the Project Explorer and will be shown in the Code Window on the right.
You can also insert a Class Module
A class module is used to insert objects into your VBA project.
Removing a Module or Form from the Project Explorer
Right-click on the module or form you wish to remove to show the right click short cut menu.
Click Remove (in this case UserForm1…)
OR
Click on the File menu, and then click on Remove (UserForm1).
A warning box will appear asking if you want to Export the form or module before you remove it. Exporting the form or module enables you to save it as an individual file for use in a different Excel project at some other time.
More often than not when you remove a module or form it is because you do not need it, so click No.
The Properties Window
You will see the properties window below the Project Explorer. You may need to switch this on.
Press F4 or click View, Properties Window.
The properties window enables you to see the properties for the particular module or form that is selected in the Project Explorer. When you are working in modules, you can use the properties window to change the name of the module. This is the only property available to a module. However, when you are working with forms, there will be far more properties available and the Properties window is then used extensively to control the behavior of forms and the controls contained in the form.
When you record a macro, it is automatically put into a standard module. The module will named ‘Module1’ and any code that is contained in that module is available to be used throughout your project. You should rename your module to something that is significant, that would make your code easy to find if you were to add multiple modules to the project.
You can also rename your forms.
If you have renamed your sheet in Excel, the name of the sheet will show up as the name of the sheet in brackets after Sheet1.
If you want to change the name of the module behind the sheet, you can change it in the same way you change the module and user form name – by changing the Name property in the Properties Window.
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
Learn More
The Code Window
The code window shows you the sub procedures and functions that are contained in your modules – it shows you the actual code. When you record a macro, a sub procedure will be created for you. If you add a short cut key to the macro, it will show up as a comment in the macro to let you know what the short cut key is that you assigned to the macro.
At the top of the code window are two combo boxes. These allow you to see which object (if any) within the Module that you might be working on, and which Procedure you might be working on.
In the example above, we are not working on any object – thus this is set to general, but we are working within the Gridlines procedure.
If we had more than one procedure in this module, we could use the combo box above to navigate to the other procedures.
Understanding the Code
There are 2 types of procedures – Sub procedures and Function procedures.
Sub Procedures
The macro recorder can only record Sub procedures. A Sub procedure does things. They perform actions such as formatting a table or creating a pivot table, or in the gridline example, changing the view settings of your active window. The majority of procedures written are Sub procedures. All macros are Sub procedures.
A sub procedure begins with a Sub statement and ends with an End Sub statement. The procedure name is always followed by parentheses.
Sub HideGridLines()
ActiveWindow.DisplayGridlines = False
End Sub
VBA Programming | Code Generator does work for you!
Function Procedures
A Function procedure returns a value. This value may be a single value, an array, a range of cells or an object. Functions usually perform some type of calculation. Functions in Excel can be used with the Function Wizard or they can be called from Sub Procedures.
Function Kilos(pounds as Double)
Kilos = (pounds/2.2)
End Function
This function could be used within the Insert Function dialog box in Excel to convert Pounds to Kilograms.
Creating a new Procedure
Before you create your new procedure, make sure you are in the module in which you wish to store the procedure. You can create a new procedure by clicking on the Insert menu, Procedure;
or you can click on the icon on the toolbar
The following dialog box will appear
- Type the name of your new procedure in the name box – this must start with a letter of the alphabet and can contain letters and number and be a maximum of 64 characters.
- You can have a Sub procedure, a Function procedure or a Property procedure. (Properties are used in Class modules and set properties for ActiveX controls that you may have created).
- You can make the scope of the procedure either Public or Private. If the procedure is public (default), then it can be used by all the modules in the project while if the procedure is private, it will only be able to be used by this module.
- You can declare local variables in this procedure as Statics (this is to do with the Scope of the variable and makes a local procedure level variable public to the entire module). We will not use this option.
When you have filled in all the relevant details, click on OK.
You then type your code between the Sub and End Sub statements.
ALTERNATIVELY – you can type the Sub and End Sub statements in your module exactly as it appears above. You do not need to put the word Public in front of the word sub – if this word is omitted, all procedures in the module are automatically assumed to be Public.
Then you type Sub and then the name of your procedure followed by parenthesis.
ie:
Sub test()
The End Sub statement will appear automatically.
Writing Code that is easy to understand and navigate
Get into the habit of putting in comments in your code in order to remind yourself at a later stage of the functionality of the code.
You can insert a comment in your code but typing an apostrophe on the keyboard or you can switch on the Edit toolbar, and use the comment button which appears on that toolbar.
Right-click on the toolbars.
Select Edit.
Click on the comment button to insert a comment into your code.
NOTE: You usually only use the comment block button when you have a few lines of code you wish to comment out (and not delete). It is easier for a single comment to use an apostrophe.
Indenting
A good habit to get into is to indent your code making it easy to read through the code and see the different parts of the code.
There can be many levels of indenting, depending on the logic of your code.
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
UpperCase vs LowerCase
VBA adjusts all code to Proper Case so if you type ALL IN UPPERCASE or all in lowercase it will Readjust Your Code To Be In Proper Case!
AutoComplete
When you adjust your code, you will notice that VBA tries to help you by suggesting the code that you can type. This is known as AutoComplete.
Error trapping and Debugging
There are 4 types of errors that can occur when you write VBA code – Syntax errors, Compilation errors, Runtime errors and Logical Errors.
Syntax errors
These occur when you write the code incorrectly. This is largely prevented by VBA by having the Syntax check option switch on. This is normally on by default but if your is switch off, then switch it on by going to Tools, Options and click Auto Syntax Check.
If you type the code incorrectly (for example excluding something that should be in the code), a message box will pop up while you are writing the code giving you the opportunity to amend the code.
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
Compilation Errors
These occur when something is missing from the code that prevents the code from running. The error does not come up when you write the code, but it occurs when you try and run the code.
Runtime Errors
These occur when you run the code, and the syntax and compilation is correct, but something else occurs to prevent the code from running correctly.
In this case, Sheet4 does not exist. This error message is more useful than the compile error messages as it gives you the opportunity to Debug the code and see why it is not working.
Click Debug. The code will stop at the error and highlight the error in yellow enabling you to correct your error.
Amend Sheet4 to Sheet2 (as Sheet 2 exists and Sheet 4 does not exist).
Press F5 or click on the Continue button on the toolbar.
Logical Errors
These are the most difficult to find. In their case, the code is written correctly but the actual logic of the code is flawed, so you may not get the result that you want from the code. For logical errors, error trapping is essential.
There are 2 types of error traps
On Error Go To
The following code is to open the File Open Dialog box – it will give us an error if the user clicks Cancel.
When you run the code the File Open dialog box appears.
When you then click cancel, the error will occur.
The following Error trap will continue the code to the Exit Function of the code, and return message.
This makes use of On Error GoTo to exit the function.
When you run the code and click cancel, the message box will appear.
On Error Resume Next
If you put the On Error Resume Next Statement into your code, the line that contains the error will be ignored and the code will continue.
For example, if the user clicks Cancel in the code below, the code will not give you a run-time error, it will just end without the code doing anything further.
There are times when this is very useful but it can also be very dangerous in some circumstances as it does not return a message as to why you obtained an error.
Содержание
- Что такое редактор Visual Basic в Excel?
- Открытие редактора VB
- Анатомия редактора Visual Basic в Excel
- Куда добавить код в редакторе VB
- Настройка редактора VB
Первым шагом к работе с VBA в Excel является ознакомление с редактором Visual Basic (также называемым редактором VBA или редактором VB).
В этом руководстве я расскажу все, что нужно знать о редакторе VBA, и некоторые полезные параметры, которые вы должны знать при кодировании в Excel VBA.
Редактор Visual Basic — это отдельное приложение, которое является частью Excel и открывается всякий раз, когда вы открываете книгу Excel. По умолчанию он скрыт, и для доступа к нему необходимо активировать его.
VB Editor — это место, где вы храните код VB.
Получить код в редакторе VB можно несколькими способами:
- Когда вы записываете макрос, он автоматически создает новый модуль в редакторе VB и вставляет код в этот модуль.
- Вы можете вручную ввести код VB в редакторе VB.
- Вы можете скопировать код из другой книги или из Интернета и вставить его в редактор VB.
Открытие редактора VB
Открыть редактор Visual Basic в Excel можно разными способами:
- Использование сочетания клавиш (самый простой и быстрый)
- Используя вкладку разработчика.
- Использование вкладок рабочего листа.
Давайте быстро пройдемся по каждому из них.
Сочетание клавиш для открытия редактора Visual Basic
Самый простой способ открыть редактор Visual Basic — использовать сочетание клавиш — ALT + F11 (удерживая клавишу ALT, нажмите клавишу F11).
Как только вы это сделаете, откроется отдельное окно для редактора Visual Basic.
Этот ярлык работает как переключатель, поэтому при повторном использовании он вернет вас в приложение Excel (без закрытия редактора VB).
Ярлык для версии Mac: Opt + F11 или Fn + Opt + F11
Использование вкладки разработчика
Чтобы открыть редактор Visual Basic с ленты:
- Перейдите на вкладку «Разработчик» (если вы не видите вкладку «Разработчик», прочтите, как ее получить).
- В группе «Код» щелкните Visual Basic.
Использование вкладки рабочего листа
Это менее используемый метод открытия редактора Vb.
Перейдите на любую из вкладок рабочего листа, щелкните правой кнопкой мыши и выберите «Просмотреть код».
Этот метод не просто откроет редактор VB, он также перенесет вас в окно кода для этого объекта рабочего листа.
Это полезно, когда вы хотите написать код, который работает только для определенного рабочего листа. Обычно это происходит с событиями рабочего листа.
Анатомия редактора Visual Basic в Excel
Когда вы открываете редактор VB в первый раз, это может показаться немного подавляющим.
Существуют различные варианты и разделы, которые сначала могут показаться совершенно новыми.
Кроме того, он все еще выглядит как старый Excel 97 дней. Хотя дизайн и удобство использования Excel значительно улучшились за последние годы, редактор VB не претерпел каких-либо изменений в своем внешнем виде.
В этом разделе я познакомлю вас с различными частями приложения Visual Basic Editor.
Примечание. Когда я начал использовать VBA несколько лет назад, меня поразили все эти новые параметры и окна. Но когда вы привыкнете работать с VBA, вы освоитесь с большинством из них. И в большинстве случаев вам не нужно будет использовать все возможности, а только ручную работу.
Ниже представлены изображения различных компонентов редактора VB. Затем они подробно описаны в следующих разделах этого руководства.
Теперь давайте быстро рассмотрим каждый из этих компонентов и поймем, что он делает:
Строка меню
Здесь у вас есть все параметры, которые вы можете использовать в редакторе VB. Это похоже на ленту Excel, где у вас есть вкладки и параметры для каждой вкладки.
Вы можете изучить доступные варианты, щелкнув каждый элемент меню.
Вы заметите, что рядом с большинством параметров в редакторе VB указаны сочетания клавиш. Как только вы привыкнете к нескольким сочетаниям клавиш, работа с редактором VB станет действительно простой.
Панель инструментов
По умолчанию в редакторе VB есть панель инструментов, на которой есть несколько полезных опций, которые могут вам понадобиться чаще всего. Это похоже на панель быстрого доступа в Excel. Это дает вам быстрый доступ к некоторым полезным параметрам.
Вы можете немного настроить его, удалив или добавив к нему параметры (щелкнув небольшую стрелку, направленную вниз, в конце панели инструментов).
В большинстве случаев панель инструментов по умолчанию — это все, что вам нужно при работе с редактором VB.
Вы можете переместить панель инструментов над строкой меню, щелкнув три серые точки (в начале панели инструментов) и перетащив ее над строкой меню.
Примечание. В редакторе VB есть четыре панели инструментов — Стандартная, Отладка, Редактировать и Пользовательская форма. То, что вы видите на изображении выше (которое также используется по умолчанию), является стандартной панелью инструментов. Вы можете получить доступ к другим панелям инструментов, перейдя к параметру «Просмотр» и наведя курсор на параметр «Панели инструментов». Вы можете добавить одну или несколько панелей инструментов в редактор VB, если хотите.
Обозреватель проекта
Обозреватель проекта — это окно слева, в котором отображаются все объекты, открытые в настоящее время в Excel.
Когда вы работаете с Excel, каждая открытая книга или надстройка является проектом. И в каждом из этих проектов может быть набор объектов.
Например, на изображении ниже в Project Explorer показаны две открытые книги (Book1 и Book2) и объекты в каждой книге (рабочие листы, ThisWorkbook и Module в Book1).
Слева от объектов есть значок плюса, который можно использовать, чтобы свернуть список объектов или развернуть и просмотреть полный список объектов.
Следующие объекты могут быть частью Project Explorer:
- Все открытые книги — в каждой книге (которая также называется проектом) вы можете иметь следующие объекты:
- Объект рабочего листа для каждого листа в книге
- ThisWorkbook объект который представляет собой книгу
- Таблица объект для каждого листа диаграммы (они не так распространены, как рабочие листы)
- Модули — Здесь идет код, созданный с помощью средства записи макросов. Вы также можете написать или скопировать код VBA сюда.
- Все открытые надстройки
Рассматривайте Project Explorer как место, где отображаются все объекты, открытые в Excel в данный момент.
Сочетание клавиш для открытия Project Explorer: Ctrl + R (удерживайте контрольную клавишу, а затем нажмите R). Чтобы закрыть его, просто щелкните значок закрытия в правом верхнем углу окна Project Explorer.
Примечание. Для каждого объекта в Project Explorer есть окно кода, в котором вы можете написать код (или скопировать и вставить его откуда-нибудь). Окно кода появляется при двойном щелчке по объекту.
Окно свойств
Окно свойств — это то место, где вы можете увидеть свойства выбранного объекта. Если у вас еще нет окна «Свойства», вы можете получить его с помощью сочетания клавиш F4 (или перейдите на вкладку «Просмотр» и нажмите «Окно свойств»).
Окно свойств — это плавающее окно, которое можно закрепить в редакторе VB. В приведенном ниже примере я закрепил его чуть ниже Project Explorer.
Окно свойств позволяет нам изменять свойства выбранного объекта. Например, если я хочу сделать рабочий лист скрытым (или очень скрытым), я могу сделать это, изменив свойство Visible для выбранного объекта рабочего листа.
Связанный: Скрытие рабочего листа в Excel (который не может быть легко отсканирован)
Окно кода
Для каждого объекта, перечисленного в Project Explorer, есть окно кода. Вы можете открыть окно кода для объекта, дважды щелкнув его в области Project Explorer.
Окно кода — это то место, где вы будете писать свой код или копировать и вставлять код из другого места.
Когда вы записываете макрос, его код попадает в окно кода модуля. Excel автоматически вставляет модуль для размещения в нем кода при записи макроса.
Связанный: Как запустить макрос (код VBA) в Excel.
Немедленное окно
Окно Immediate в основном используется при отладке кода. Один из способов использования окна Immediate — использование оператора Print.Debug в коде с последующим запуском кода.
Это помогает мне отлаживать код и определять, где мой код застревает. Если я получаю результат Print.Debug в непосредственном окне, я знаю, что код работал, по крайней мере, до этой строки.
Если вы новичок в кодировании VBA, вам может потребоваться некоторое время, чтобы использовать немедленное окно для отладки.
По умолчанию непосредственное окно не отображается в редакторе VB. Вы можете получить его, используя сочетание клавиш Control + G (или можете перейти на вкладку «Просмотр» и нажать «Немедленное окно»).
Куда добавить код в редакторе VB
Я надеюсь, что теперь у вас есть общее представление о том, что такое VB Editor и какие в нем части.
В этом разделе этого руководства я покажу вам, где добавить код VBA в редактор Visual Basic.
Есть два места, где вы можете добавить код VBA в Excel:
- Окно кода для объекта. Этими объектами могут быть рабочая книга, рабочий лист, пользовательская форма и т. Д.
- Окно кода модуля.
Окно кода модуля против окна кода объекта
Позвольте мне сначала быстро пояснить разницу между добавлением кода в модуль и добавлением кода в окне объектного кода.
Когда вы добавляете код к любому из объектов, он зависит от какого-либо действия этого объекта, которое запускает этот код. Например, если вы хотите отобразить все рабочие листы в книге, как только вы откроете эту книгу, тогда код будет помещен в объект ThisWorkbook (который представляет книгу).
В данном случае триггер открывает книгу.
Точно так же, если вы хотите защитить рабочий лист, как только активируется какой-либо другой рабочий лист, код для этого будет помещен в окно кода рабочего листа.
Эти триггеры называются событиями, и вы можете связать код, который будет выполняться при возникновении события.
Связанный: Узнайте больше о событиях в VBA.
Напротив, код в модуле должен выполняться вручную (или его также можно вызывать из других подпрограмм).
Когда вы записываете макрос, Excel автоматически создает модуль и вставляет в него записанный код макроса. Теперь, если вам нужно запустить этот код, вам нужно вручную выполнить макрос.
Добавление кода VBA в модуль
При записи макроса автоматически создается модуль и вставляется в него код, однако при использовании средства записи макросов существуют некоторые ограничения. Например, он не может использовать циклы или условия If Then Else.
В таких случаях лучше либо скопировать и вставить код вручную, либо написать код самостоятельно.
Модуль может использоваться для хранения следующих типов кодов VBA:
- Декларации: Вы можете объявлять переменные в модуле. Объявление переменных позволяет указать, какой тип данных может содержать переменная. Вы можете объявить переменную только для подпрограммы или для всех подпрограмм в модуле (или всех модулях)
- Подпрограммы (процедуры): Это код, в котором есть шаги, которые вы хотите выполнить с помощью VBA.
- Функциональные процедуры: Это код, который возвращает одно значение, и вы можете использовать его для создания пользовательских функций (также называемых пользовательскими функциями или UDF в VBA).
По умолчанию модуль не является частью книги. Вам необходимо вставить его перед использованием.
Добавление модуля в редактор VB
Ниже приведены шаги по добавлению модуля:
- Щелкните правой кнопкой мыши любой объект книги (в котором вы хотите установить модуль).
- Наведите курсор на опцию Вставить.
- Щелкните по модулю.
Это мгновенно создаст папку с именем Module и вставит объект с именем Module 1. Если у вас уже есть вставленный модуль, вышеупомянутые шаги будут вставлять другой модуль.
После того, как модуль вставлен, вы можете дважды щелкнуть объект модуля в Project Explorer, и он откроет для него окно кода.
Теперь вы можете скопировать и вставить код или написать его самостоятельно.
Удаление модуля
Ниже приведены шаги по удалению модуля в Excel VBA:
- Щелкните правой кнопкой мыши модуль, который хотите удалить.
- Нажмите на опцию «Удалить модуль».
- В открывшемся диалоговом окне нажмите Нет.
Примечание. Вы можете экспортировать модуль перед его удалением. Он сохраняется как файл .bas, и вы можете импортировать его в другой проект. Чтобы экспортировать модуль, щелкните модуль правой кнопкой мыши и выберите «Экспорт файла».
Добавление кода в окно объектного кода
Чтобы открыть окно кода для объекта, просто дважды щелкните по нему.
Когда он откроется, вы можете ввести код вручную или скопировать и вставить код из других модулей или из Интернета.
Обратите внимание, что некоторые объекты позволяют выбрать событие, для которого вы хотите написать код.
Например, если вы хотите написать код, чтобы что-то происходило при изменении выбора на листе, вам нужно сначала выбрать листы из раскрывающегося списка в верхнем левом углу окна кода, а затем выбрать событие изменения из раскрывающегося списка. -вниз справа.
Примечание: эти события относятся к объекту. Когда вы откроете окно кода для книги, вы увидите события, связанные с объектом книги. Когда вы откроете окно кода для рабочего листа, вы увидите события, связанные с объектом рабочего листа.
Настройка редактора VB
Хотя настройки редактора Visual Basic по умолчанию достаточно хороши для большинства пользователей, они позволяют дополнительно настраивать интерфейс и некоторые функции.
В этом разделе руководства я покажу вам все параметры, которые у вас есть при настройке редактора VB.
Чтобы настроить среду редактора VB, нажмите «Инструменты» в строке меню, а затем нажмите «Параметры».
Это откроет диалоговое окно Параметры, которое предоставит вам все параметры настройки в редакторе VB. В диалоговом окне «Параметры» есть четыре вкладки (как показано ниже), на которых можно настроить различные параметры редактора Visual Basic.
Давайте быстро рассмотрим каждую из этих вкладок и важные параметры на каждой из них.
Вкладка «Редактор»
Хотя встроенные настройки в большинстве случаев работают нормально, позвольте мне все же пройтись по параметрам на этой вкладке.
По мере того, как вы станете более опытным в работе с VBA в Excel, вы можете настроить редактор VB, используя некоторые из этих параметров.
Автоматическая проверка синтаксиса
При работе с VBA в Excel, как только вы сделаете синтаксическую ошибку, вас встретит всплывающее диалоговое окно (с некоторым описанием ошибки). Что-то вроде того, что показано ниже:
Если вы отключите эту опцию, это всплывающее окно не появится, даже если вы допустили синтаксическую ошибку. Однако цвет текста кода изменится, что укажет на наличие ошибки.
Если вы новичок, я рекомендую оставить эту опцию включенной. По мере того, как вы набираетесь опыта в программировании, вы можете начать находить эти всплывающие окна раздражающими, и тогда вы можете отключить эту опцию.
Требовать объявление переменной
Это один из вариантов, который я рекомендую включить.
Когда вы работаете с VBA, вы будете использовать переменные для хранения различных типов данных и объектов.
Когда вы включаете этот параметр, он автоматически вставляет оператор «Option Explicit» в верхнюю часть окна кода. Это заставляет вас объявить все переменные, которые вы используете в своем коде. Если вы не объявите переменную и попытаетесь выполнить код, отобразится ошибка (как показано ниже).
В приведенном выше случае я использовал переменную Var, но не объявлял ее. Поэтому, когда я пытаюсь запустить код, он показывает ошибку.
Эта опция очень полезна, когда у вас много переменных. Это часто помогает мне найти имена переменных с ошибками, поскольку они считаются необъявленными и отображается ошибка.
Примечание. Когда вы включаете этот параметр, он не влияет на существующие модули.
Автоматический член списка
Эта опция весьма полезна, поскольку помогает получить список свойств методов для объекта.
Например, если я хочу удалить лист (Sheet1), мне нужно использовать строку Sheet1.Delete.
Пока я набираю код, как только я набираю точку, он покажет мне все методы и свойства, связанные с объектом Worksheet (как показано ниже).
Функция автоматического списка хороша тем, что позволяет:
- Быстро выберите свойство и метод из списка и сэкономьте время
- Показывает все свойства и методы, о которых вы, возможно, не знали.
- Избегайте орфографических ошибок
Эта опция включена по умолчанию, и я рекомендую оставить ее в таком состоянии.
Параметры автоматической быстрой информации
Когда вы вводите функцию на листе Excel, она показывает вам некоторую информацию о функции, например, аргументы, которые она принимает.
Точно так же, когда вы вводите функцию в VBA, она показывает вам некоторую информацию (как показано ниже). Но для этого вам нужно убедиться, что опция Auto Quick Info включена (что по умолчанию).
Параметры советов по автоматическим данным
Когда вы просматриваете свой код построчно и помещаете курсор над именем переменной, он покажет вам значение переменной.
Я считаю это весьма полезным при отладке кода или при просмотре кода построчно, в котором есть циклы.
В приведенном выше примере, как только я наведу курсор на переменную (var), отобразится значение, которое она содержит.
Этот параметр включен по умолчанию, и я рекомендую вам оставить его в таком же состоянии.
Автоматический отступ
Поскольку коды VBA могут быть длинными и беспорядочными, использование отступов увеличивает читаемость кода.
При написании кода вы можете делать отступ с помощью клавиши табуляции.
Этот параметр гарантирует, что, когда вы закончите с отступом и нажмете Enter, следующая строка не начнется с самого начала, а будет иметь тот же отступ, что и предыдущая.
В приведенном выше примере после того, как я напишу строку Debug.Print и нажму Enter, она начнется прямо под ней (с тем же уровнем отступа).
Я считаю эту опцию полезной, и ее выключение означало бы вручную отступ каждой строки в блоке кода, который я хочу иметь отступ.
При желании вы можете изменить значение отступа. Я сохраняю значение по умолчанию.
Редактирование текста перетаскиванием
Когда этот параметр включен, он позволяет выбрать блок кода и перетащить его.
Это экономит время, так как вам не нужно сначала вырезать, а потом вставлять. Вы можете просто выбрать и перетащить его.
Этот параметр включен по умолчанию, и я рекомендую вам оставить его в таком же состоянии.
По умолчанию — полный вид модуля
Когда эта опция включена, вы сможете увидеть все процедуры в модуле в одном прокручиваемом списке.
Если вы отключите эту опцию, вы сможете видеть только один модуль за раз. Вам нужно будет выбрать модуль, который вы хотите увидеть, из раскрывающегося списка в правом верхнем углу окна кода.
Этот параметр включен по умолчанию, и я рекомендую оставить его в таком же состоянии.
Одна из причин, по которой вы можете захотеть отключить его, когда у вас есть несколько процедур, которые огромны и прокрутка по ним требует времени, или когда у вас много процедур, и вы хотите быстро найти их, а не тратить время на прокрутку.
Разделитель процедур
Когда эта опция включена, вы увидите линию (своего рода разделитель) между двумя процедурами.
Я считаю это полезным, поскольку он визуально показывает, когда заканчивается одна процедура и начинается другая.
Он включен по умолчанию, и я рекомендую оставить его в таком состоянии.
Вкладка «Формат редактора»
С помощью параметров на вкладке «Формат редактора» вы можете настроить внешний вид кода в окне кода.
Лично я сохраняю все параметры по умолчанию, так как меня это устраивает. Если вы хотите, вы можете настроить это в зависимости от ваших предпочтений.
Чтобы внести изменения, вам нужно сначала выбрать параметр в поле «Цвета кода». После выбора параметра вы можете изменить для него цвет переднего плана, фона и индикатора.
На этой вкладке также можно установить тип и размер шрифта. Рекомендуется использовать шрифт фиксированной ширины, например Courier New, так как он делает код более читабельным.
Обратите внимание, что настройки типа и размера шрифта останутся одинаковыми для всех типов кода (т. Е. Для всех типов кода, показанных в поле цвета кода).
Ниже приведено изображение, на котором я выбрал точку останова и могу изменить ее форматирование.
Примечание. Параметр «Полоса индикатора полей», когда он включен, показывает небольшую полоску полей слева от кода. Это полезно, так как показывает полезные индикаторы при выполнении кода. В приведенном выше примере, когда вы устанавливаете точку останова, она автоматически показывает красную точку слева от строки на полосе полей. В качестве альтернативы, чтобы установить точку останова, вы можете просто щелкнуть полосу полей слева от строки кода, которую вы хотите использовать в качестве точки останова.
По умолчанию полоса индикатора маржи включена, и я рекомендую оставить ее в таком состоянии.
Одна из моих студенток курса VBA нашла эти параметры настройки полезными, и она была дальтоник. Используя параметры здесь, она смогла установить цвет и форматы, которые упростили ей работу с VBA.
Вкладка Общие
На вкладке «Общие» есть много параметров, но изменять их не нужно.
Я рекомендую вам оставить все параметры как есть.
Одна из важных опций, о которых следует знать на этой вкладке, — это обработка ошибок.
По умолчанию выбран параметр «Прерывание по необработанным ошибкам», и я рекомендую оставить его таким же.
Этот параметр означает, что если ваш код обнаружит ошибку, и вы еще не обработали эту ошибку в своем коде, он сломается и остановится. Но если вы устранили ошибку (например, с помощью параметров «При ошибке возобновить следующий» или «При ошибке Перейти к»), то она не сломается (поскольку ошибки не обрабатываются).
Вкладка стыковки
На этой вкладке вы можете указать, какие окна вы хотите закрепить.
Закрепление означает, что вы можете зафиксировать положение окна (например, проводника проекта или окна свойств), чтобы оно не перемещалось, и вы могли просматривать все различные окна одновременно.
Если вы не установите док-станцию, вы сможете просматривать одно окно за раз в полноэкранном режиме, и вам придется переключаться на другое.
Я рекомендую оставить настройки по умолчанию.
ВикиЧтение
VBA для чайников
Каммингс Стив
Вызов редактора Visual Basic
Редактор Visual Basic служит командным центром для работы в VBA. В нем вы должны находиться при разработке VBA-форм, создании VBA-кода, тестировании и отладке VBA программ. Экспертом по использованию редактора Visual Basic вы станете после прочтения главы 5, а пока вам нужно только знать, как вытянуть этот редактор на экран.
Если вы делали кое-что из того, о чем так много говорилось в предыдущей главе при обсуждении программного кода, создаваемого средством записи макросов, вы должны уже знать один из способов вызова редактора Visual Basic- выбор макроса в диалоговом окне
Макрос с последующим щелчком на кнопке Изменить. Но, конечно же, можно запустить редактор Visual Basic и непосредственно. В большинстве VBA-приложений можно воспользоваться одним из следующих методов.
* Выбрать из меню Сервис=Макрос=Редактор Visual Basic.
* Нажать Alt+Fll. Вы услышите, как затараторит жесткий диск, и через несколько мгновений на экране появится редактор Visual Basic. Он должен хотя бы отдаленно напоминать то, что изображено на рис. 3.1.
В некоторых приложениях вам понадобится проделать другой маршрут, чтобы добраться до редактора Visual Basic. Однако вы в любом случае найдете необходимую команду где-нибудь в меню Tools (Сервис).
Вызов редактора Visual Basic одним щелчком
Если в вашем приложении есть кнопка в панели инструментов для вызова редактора Visual Basic. используйте се. В VBА-приложениях из пакета Microsoft Office (Word. Excel и PowerPoint) эта кнопка помещена в панель инструментов Visual Basic (рис. 3.2). Наборы кнопок в этой панели инструментов у разных приложений могут немного отличаться.
Рис. 3.1. Редактор Visual Basic
Рис, 3.2. Вид панели инструментов Visual Basic в приложении Word
Кнопки в этой панели инструментов, как правило, соответствуют пунктам подменю Макрос из меню Сервис. Вот для чего предназначены некоторые из этих кнопок (слева направо, см. рис. 3.2).
* Первые две кнопки предназначены соответственно для выполнения и записи макросов.
* Кнопка справа от кнопки Безопасность вызывает редактор Visual Basic. Если вы часто используете редактор Visual Basic, а другие кнопки в этой панели инструментов вам не нужны, скопируйте кнопку вызова редактора в другую панель. Чтобы скопировать кнопку в любом из приложений Office, перетащите ее на новое место, удерживая при этом нажатой клавишу Alt.
* Кнопка с изображенными на ней молотком и гаечным ключом открывает панель элементов управления, очень похожую на панель элементов управления VBA. В Office вы можете поместить элементы управления VBA в сам документ, а не только в VBA-форму.
* Кнопка с изображенными на ней линейкой, треугольником и карандашом включает режим проектирования, в котором вы можете редактировать элементы управления VBA в своем документе.
Читайте также
Visual Basic 6.0
Visual Basic 6.0
В Visual Basic 6.0 в отличие от пятой версии окна Code и Object появляются в нормальном, не в раскрытом виде. И приходится при каждом запуске VB6 раскрывать эти окна. Можно заставить автоматически раскрывать эти окна при каждом запуске. Создайте в соответствующем разделе
Visual Basic
Visual Basic
Регистрация dll- и ocx-файловДанная заметка будет полезна разработчикам. Если вам часто приходится работать с ocx-файлами (а также с dll-файлами), которые требуют регистрации в реестре с помощью REGSVR.EXE, то будет гораздо удобнее внести соответствующую запись в реестр, чем
Delphi и Visual Basic
Delphi и Visual Basic
1. Есть ли в Delphi эквивалент массива элементов управления из Visual Basic? Hет. Компоненты Delphi не имеют свойства Index, подобное VB. Однако, имеются три основные причины, почему вы хотите использовать их в VB, и для каждой из них есть решение в Delphi. Причина 1. Вы хотите
3. Переменные Visual Basic
3. Переменные Visual Basic
В Visual Basic переменные накапливают информацию (значения). При их применении Visual Basic занимают область в памяти компьютера, которая предназначена для сохранения этой информации. Имена переменных, составленные из символов, могут иметь длину в 255 символов.
Что визуального в Visual Basic для приложений?
Что визуального в Visual Basic для приложений?
К счастью, VBA во многом избавляет от необходимости нудного печатания программного кода. В одних случаях вы записываете команды, которые нужны в приложении, и используете их в качестве отправной точки при создании новой программы.В
VBA против Visual Basic
VBA против Visual Basic
Помимо того, что VBA не позволяет вам создавать отдельные приложения, одно из основных отличий состоит в том, что программы, написанные на VBA, работают медленнее, чем программы, написанные на Visual
Почему VBA обычно медленнее, чем Visual Basic
Почему VBA обычно медленнее, чем Visual Basic
Кроме того, что вы не можете создавать в VBA отдельные, автономно работающие приложения, между VBA и Visual Basic есть еще одно серьезное отличие- VBA-программы обычно выполняются медленнее.Причина этого обнаруживается просто: VBA-программу
Различия между VBA и Visual Basic
Различия между VBA и Visual Basic
VBA имеет очень много общего с Visual Basic, своим старшим братом, предназначенным для создания независимых приложений. А раз языки похожи, вы можете перенести большую часть своих навыков в программировании на VBA в Visual Basic. Однако вам следует помнить о
Вызов редактора Visual Basic одним щелчком
Вызов редактора Visual Basic одним щелчком
Если в вашем приложении есть кнопка в панели инструментов для вызова редактора Visual Basic. используйте се. В VBА-приложениях из пакета Microsoft Office (Word. Excel и PowerPoint) эта кнопка помещена в панель инструментов Visual Basic (рис. 3.2). Наборы кнопок в этой
Пользовательский интерфейс редактора Visual Basic
Пользовательский интерфейс редактора Visual Basic
Редактор Visual Basic является стандартным блюдом Microsoft- меню, панели инструментов и комбинации клавиш выглядят и работают очень похоже на Microsoft Office. Вы будете чувствовать себя как дома, если используете VBA с приложениями из Office.С
9.3. Редактор Visual Basic
9.3. Редактор Visual Basic
После записи рассмотренного выше макроса к шаблону Normal добавился следующий текст макроса:
Sub Arial_10_bold()
“
“ Arial_10_bold Macro
“ Arial 10 Полужирный
“
With Selection.Font
.Name = «Arial»
.Size = 10
.Bold = True
.Italic = False
.Underline = wdUnderlineNone
.UnderlineColor = wdColorAutomatic
.StrikeThrough = False
.DoubleStrikeThrough = False
.Outline =
Подход Visual Basic 6.0
Подход Visual Basic 6.0
Благодаря искреннему желанию насладиться более простой жизнью, многие программисты ушли от «мира каркасов» приложений на базе C(++) к более дружественным языкам, таким, как, например, Visual Basic 6.0 (VB6). Язык VB6 стал популярным благодаря тому, что он дает
Среда разработки eMbedded Visual Basic 3.0
Среда разработки eMbedded Visual Basic 3.0
Для краткости в этой главе для обозначения среды eMbedded Visual Basic 3.0 будет использовано сокращение eVB.Запустить eVB можно либо при помощи команды меню Пуск (Пуск ? Программы ? Microsoft eMbedded Visual Tools ? eMbedded Visual Basic 3.0), либо найти в папке установки
Отличия eVB и Visual Basic для. NET
Отличия eVB и Visual Basic для. NET
В основном отличия VB.NET от eVB связаны с интеграцией языка VB с Compact Framework и определяются именно внутренней структурой самой CF.Типы данныхВ eVB был один-единственный тип данных на все случаи жизни, Variant, который достался eVB по наследству от VB Script. Visual
2.4.2. Генерация кода в Visual Basic
2.4.2. Генерация кода в Visual Basic
ERwin поддерживает генерацию кода для MS Visual Basic версий 4.0 и 5.0. В качестве источника информации при генерации форм служит модель ERwin. Использование ERwin позволяет одновременно описывать как клиентскую часть (объекты, отображающие данные на экране),
This Excel tutorial explains how to open the Visual Basic Editor in Excel 2016 (with screenshots and step-by-step instructions).
How to open the VBA environment
You can access the VBA environment in Excel 2016 by opening the Microsoft Visual Basic for Applications window.
First, be sure that the Developer tab is visible in the toolbar in Excel.
The Developer tab is the toolbar that has the buttons to open the VBA editor and create Form/ActiveX Controls like buttons, checkboxes, etc.
To display the Developer tab, click on File in the menu bar and select Options from the drop down menu.
When the Excel Options window appears, click on the Customize Ribbon option on the left. Click on the Developer checkbox under the list of Main Tabs on the right. Then click on the OK button.
Select the Developer tab from the toolbar at the top of the screen. Then click on the Visual Basic option in the Code group.
Now the Microsoft Visual Basic for Applications editor should appear and you can view your VBA code.
Excel VBA is a powerful tool which enables the automation of tasks in Excel. It can be used to automate many repetitive tasks along with more complex applications. This quick tip guide shows you how to open the Excel Visual Basic Editor (aka Excel VBA Editor) and get started with VBA programming in Excel. Having access to the VBA editor lets you write your own VBA code or review recorded macros. Read on to see How to Open and Start Using the MS Excel VBA Editor
To open Excel visual basic editor,
Click the visual basic button on the developer tab.
If the Developer tab is not present, go to File -> Options -> customize ribbon and tick Developer.
You can also open VBA in Excel using Alt + F11 keyboard shortcut.
What is the VBA Editor
Great, now you’re in the editor, what is it? Microsoft Excel’s Visual basic editor can be referred to as, VBA editor, VB editor and even VBE. It is all the same thing. It’s the place where you can create macros and write scripts in Excel VBA.
The most basic sections of the editor is the Project View in which you can see modules listed down the left hand side. Think of this like a folder for your macros. Modules contain the code that is required for your macros to work. Its beyond the scope of this article to go into how to split out your code into objects but modules gives the user a powerful tool to create efficient and well organized code.
To get started writing code you will need to create a new module. Add a new module in VBA editor by clicking on VBAProject(Book1), right click, Insert Model. Delete a module by simply right clicking, Remove Module. Excel will prompt you to confirm before deleting.
Record a Macro in Excel
Recording a macro in Excel is a great way to automate tasks as well as a great tool to help learn more VBA code. A common trick is to record a macro and then review the VBA code to see how it works. Now you know how to open the VBA editor in Excel you should be able to record a macro, open the editor and view the code. You’ll see the system generated VBA can be messy but it will give you the key snippets of code needed for the desired action. These can be things as simple as formatting, copying, pasting, deleting or selecting a sell. Alternatively, you could get quite advanced and carry out entire tasks before going into the Excel visual basic editor to review the code.
The world really is your oyster when you get started recording macros in excel. Top tip is to start with small steps. You can always bulk all your small macros into one at a later stage but when it comes to reviewing each step its useful to keep it separate, at least when you are first getting started.
Run a Macro in Excel VBA Editor
Once you have entered the VBA editor, created a module and written some code you will want to run the code.
To run VBA code in VBA editor simply click the Run Macro button which is shaped like a small green triangle on the toolbar. You can also Run Macro in Excel VBA editor by pressing F5 shortcut.
This is a very quick introduction to show you how to open VBA in excel, create a new module and also run your macro once written. To write some actual code, as we have suggested above, a great tip is to record macros and then go back and review the code in the MS Excel VBA editor. You’ll be surprised how messy the generated VBA can get but it will give you the key snippets of VBA code you need to get started with Excel VBA programming and is a great way of learning the syntax of VBA. Alternatively, Google is your best friend when it comes to writing macros. So what are you waiting for, press Alt + F11 in Excel and get coding in VBA!
What to do next? REad our quick Introduction to VBA for MS Excel
Visual Basic for Applications (VBA) is a form of the Visual Basic programming language integrated into all Microsoft Office products. You can create add-on components within your basic Excel 2019 spreadsheet to create additional functionality. VBA can get complicated, but knowing how to create basic code and functionality can improve your spreadsheet’s usefulness and automate certain activity that would take hours of time.
Enabling the Developer Tab in Excel 2019
To use VBA, you need the «Developer» tab enabled. The «Developer» tab has several buttons and features that enhance the way you create spreadsheets. If you don’t have the «Developer» tab enabled, follow these next steps to enable it.
Click the «File» ribbon tab, and then click the «Options» link that shows in the bottom-left section of the Excel window. This opens a new configuration window where you can set preference for different elements of Excel. Click the «Customize Ribbon» option in the left panel.
(Excel options and configuration window)
In the image above, notice that the developer option is checked in the far right panel. This check box enables the «Developer» tab in your Excel view. Click «OK» to enable the tab and return to your Excel 2019 interface.
(VBA button location)
You should now see an additional tab marked «Developer» in the list of Excel 2019 menu options. Click this tab, and you’ll see the VBA button available on the left side.
Creating a Button on Your Spreadsheet
When you want to use VBA on your spreadsheet, buttons are one of the most common elements that you add to your document. With a button, you can trigger an event and use it to perform an action.
Components for VBA actions are found in the «Developer» tab in the «Insert» button dropdown.
(Form and ActiveX components for VBA)
When you click the «Insert» button, a dropdown displays all of the available components that you can add to your spreadsheets. The top-left control in the «Form Controls» section has the button control. You can hover your mouse over each of the components in the list to see what you can add to a spreadsheet. If you are familiar with HTML web page components, then you will recognize most of the available components in the dropdown.
Click the button control and then you can draw the button on your spreadsheet. Drawing a button lets you make it as large as small as you want. After you draw the button, a window opens where you can assign a macro.
(Assign macro window)
Click «OK» and the window closes. Now you see a button on your spreadsheet with the label «Button 1.» You can change the label on the newly created button by right-clicking the button and selecting «Edit Text.» This action prompts you for the new button name. Type a new name for your button. In this example, we’ve used the text «My Button» for the button text.
(A new button with custom text)
You can click the button if you want, and an error message with display telling you that you haven’t created a macro for it yet. This is because you haven’t created the code that will run when the button is clicked. The button serves no purpose, but you can create the macro that runs when it’s pushed, which then removes the error when you click the button.
Right click the button and choose «Assign Macro.» This action opens a Visual Basic for Applications workspace. The workspace is tied to the workbook that you have open, but you can make full applications that tie with your spreadsheet using VBA. In this workspace, you can create, test, and run any code that you assign to components in your application.
Working in the VBA Workspace
The VBA workspace looks the same whether you program macros in Word or Excel. It’s a workspace where you can program the macro and view all other code that you’ve previously created.
(VBA workspace)
The image above shows the VBA workspace. When you right click a component such as a button and choose «Edit Code,» VBA opens to the location where code is triggered when you click the button. VBA gives names to these functions that help you identify what happens should you perform an activity on it. Since a button is usually triggered by a click event, the function is given the original name of the button, an underscore, and then the word «Click.» For your first button created in your spreadsheet, the name for a click event is «Button1_Click()» and you add any code between the «Sub» and «End Sub» phrases.
The «Sub» keyword indicates that you are starting an event. The next part is the name of the event, and the last statement in a trigger event is the «End Sub» statement.
In the left panel of the workspace, you can see other objects in a tree view. The top object is always the workbook. If you recall, a workbook contains worksheet. Under the «Book1» main project header, you see «ThisWorkbook» which represents the workbook that you have opened, and the «Sheet1» represents the worksheet in the workbook. You can write VBA that works directly on a workbook or a worksheet activity such as when you open the workbook, a macro automatically runs.
The «Modules» section holds the files that you store containing VBA code. You can have several of these in your VBA code, or you can just have one file that contains all of the functions used to run macros.
Writing Some Simple VBA Code
With the VBA editor open, you now have a function ready to edit for your button. Anything you type in the «Sub» and «End Sub» statements will run when you click the Button1 component. When you start working with VBA, you want to create easy function statements so that you can follow what is going on as the code runs. In this example, we’ll add some text to a cell within the current spreadsheet.
Within the sub start and end phrases, type the following code:
Sub Button1_Click()
Range(«A1»).Value = «My Test»
End Sub
The code above tells Excel 2019 that you want to change the value contained in the cell «A1» in the current sheet to «My Test.» The «Range» indicates that you want to apply changes to a cell range set in the functions parameters. You can assign any value to a range, but in this example we apply text. Any formatting already set on the cell will also still apply, so if you have a cell set to bold text, then this value will have the bold format applied.
At the top of the VBA workspace, notice that there are three start, pause and stop buttons. You can use these buttons to test your new code. The «start» button will run the current function and apply changes to the spreadsheet, which in this example is changing content to «My Test.»
(The start button in the VBA workspace)
Click the start button and watch the text in the A1 cell change to «My Test.» Should you have a long list of statements within your function, you might want to pause the procedure. The stop button stops execution, so should you resume it then execution will start where it left off. With the pause button, execution resumes where the last statement left off.
The «MsgBox» function is extremely common in any application. The MsgBox function displays a warning or a message to the user. In any software application, you’ve seen pop-up windows that display a message that provides information. Even web applications display messages as pop-ups and warnings. The MsgBox function in VBA is the equivalent of all of these pop-ups that you’ve seen across different applications.
Suppose that you want to show a confirmation to the user that the button’s function completed execution. In this example, only one statement executes, but you might have hundreds of lines of code that must execute and you want to show the user that it’s completed. You might have a procedure that takes an unusual amount of time to complete, so users must wait for it to complete and then you display the message to confirm when the procedure is over.
Add the next line of code to the same VBA function Button1_Click():
Sub Button1_Click()
Range(«A1»).Value = «My Test»
MsgBox «Cell value change finished»
End Sub
In the code above, the cell A1 has its value changed to «My Test.» After the text is changed in the A1 cell, a message box opens and displays the text «Cell value change finished.» This is just a small example of how you can use the MsgBox function. After you finished changing your VBA code, click the play button again. You will see the two statements run, and the program will stop.
After you are finished writing your code, you still need to save it and test it within the spreadsheet. Your users won’t open the VBA workspace, so you need to make sure that the code executes outside of the VBA workspace.
Close the VBA workspace. You now need to assign the macro to the button. Right-click the button and click «Assign Macro.» Choose the Button1_Click value and click «OK.» Should you ever want to go back and change the statements executed by the macro. Use this screen to click the macro name, and then click «Edit» to again open the VBA workspace with the function code shown in the workspace window.
After the window closes, click the button. Notice that the text in cell A1 changes and then a window displays with a message that the procedure has completed. You’ve just created your first VBA macro that runs in your spreadsheet. You can create much more complex applications with VBA that run across several spreadsheets and can affect several other workbooks that aren’t even open on your desktop.
One issue to remember with VBA is that it’s a powerful tool that can do harm if it’s used the wrong way. Malware writers use VBA macros to download malicious software and install it on your computer. When you work with macros, your recipients of any spreadsheet must give your macros permission to run on their machines. Most users are trained not to open spreadsheets with macros, so they are mostly used within the same organization.
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, in practice, you’re likely to constantly work with the VBE on your way to becoming a proficient VBA user.
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.
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.
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.
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 practice, there are different opinions.
- Some advanced VBE users use the default settings.
- However, other advanced VBA users display several 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 is (basically/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. You’re likely to (eventually) work with the Properties Window, particularly in the context of creating UserForms. 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. The main 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, 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.
- Editor Format.
- General.
- Docking.
Editor Tab
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.
Code Settings
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 advanced VBA users are of the opinion that Auto Syntax Check should be disabled. The main reason for this is that the VBE highlights the error by (by default) using red font. In this context, the message box displayed by the VBE may be redundant.
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:
Option Explicit
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 advanced VBA users say that you should enable Require Variable Declaration. One of the (main) benefits of enabling Require Variable Declaration is the fact it reduces the risk of errors arising out of misspelled variable names.
The case for enabling Require Variable Declaration is even stronger if you’re beginning to use the VBE. In this context, Require Variable Declaration (usually) saves you time when debugging and improves your understanding of Visual Basic for Applications.
Despite the above, some advanced Excel users 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, including the following:
- 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. This is particularly useful in the context of debugging.
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 advanced VBA users use a different number of spaces (usually less than 4) 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 advanced VBA users suggest that if you’re not using a fixed width font (as I suggest below), it may advisable to increase the number of characters (used to indent) 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.
Appropriate indentation is very important. Therefore, you’ll probably want to enable Auto Indent and set a tab width that works well for your particular circumstances and VBE settings.
Window 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.
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 very common.
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 the same amount of horizontal space.
This (usually) enhances the readability of your VBA code. For example:
- All characters are appropriately aligned; and
- You can (more) easily identify multiple or missing spaces.
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.
General Tab
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.
When you’re starting to work with the VBE, the default settings in this tab (usually) work well enough.
Setting #1: Form Grid Settings.
Form Grid Settings allow you to control the way in which the VBE handles UserForms. This is a more advanced topic that I may cover in future tutorials.
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. This (generally) 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.
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 several advanced VBA users.
- “Break on Unhandled Errors” is the default setting. This is also the choice suggested by several advanced VBA users. 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). More precisely:
- VBA code must be compiled before it can be executed; but
- Not (absolutely) all VBA code in a project must be compiled before certain (usually the initial) parts of the VBA code can start running.
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, you won’t 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.
Docking Tab
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 the Properties Window 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 2 methods explained below. As a general rule, you can only remove VBA modules. You cannot remove other code modules, such as those for:
- Worksheets (Sheet#); or
- The workbook (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:
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. In most cases, you can simply do the following to have 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”:
Conclusion
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
- Walkenbach, John (2013). Excel VBA Programming for Dummies. Hoboken, NJ: John Wiley & Sons Inc.
- Walkenbach, John (2013). Excel 2013 Power Programming with VBA. Hoboken, NJ: John Wiley & Sons Inc.
В этой главе даётся очень краткий обзор редактора Visual Basic в Excel. Если Вы любознательный читатель и хотите узнать еще больше информации о редакторе, то при желании без проблем найдете ресурсы с более подробным описанием.
Содержание
- Запуск редактора Visual Basic
- Окна редактора Visual Basic
- Окно проекта (Project)
- Окно кода (Code)
- Окно свойств (Properties)
- Окно отладчика (Immediate)
- Окно переменных (Locals)
- Окно отслеживания (Watches)
Запуск редактора Visual Basic
Простейший способ запустить редактор Visual Basic в Excel – нажать комбинацию клавиш Alt+F11 (то есть нажать клавишу Alt и, удерживая её, нажать клавишу F11). После этого откроется окно редактора Visual Basic, как показано на картинке ниже. Имейте ввиду, что окно Excel остается открытым и находится позади окна редактора.
Окна редактора Visual Basic
В процессе работы в редакторе Visual Basic в Excel могут быть открыты различные окна. Управление окнами осуществляется в меню View, которое находится в верхней части окна редактора VBA. Ниже дано описание отдельных окон.
Окно проекта (Project)
Окно Project открывается в левой части редактора VBA (показано на картинке выше). В этом окне для каждой открытой рабочей книги создаётся проект VBA (VBA Project). Проект VBA – это набор всех объектов и модулей VBA, привязанных к текущей книге. Изначально в него входят:
- Объект ЭтаКнига (ThisWorkbook), привязанный к книге Excel;
- Объекты Лист (Sheet), привязанные к каждому листу текущей рабочей книги Excel.
Самостоятельно в проект можно добавить объекты Userform, Module и Class Module. Если Вы посмотрите на картинку выше, то увидите, что в проект VBA для книги Book1.xlsm добавлен объект Module с названием Module1.
Вот как можно создать новый объект Userform, Module или Class Module:
- В окне Project выберите рабочую книгу, в которую нужно добавить объект, и кликните по ней правой кнопкой мыши.
- В появившемся меню кликните Insert и в раскрывшемся меню выберите Userform, Module или Class Module.
Для каждого из описанных выше объектов предусмотрено специальное окно, в котором будет создаваться и храниться новый код VBA. Порядок при этом такой:
- Код, который относится к рабочей книге, должен быть введён в соответствующий объект ЭтаКнига (ThisWorkbook);
- Код, который относится к рабочему листу, должен быть введён в соответствующий объект Лист (Sheet);
- Код более общего характера должен быть введён в Module;
- Код для нового объекта должен быть введён в Class Module;
- Если нужно создать диалоговое окно для взаимодействия с пользователем, то можно использовать Userform.
Окно кода (Code)
Двойной щелчок мышью по любому объекту в окне Project открывает соответствующее окно Code, предназначенное для ввода кода VBA с клавиатуры. На одном из приведённых выше рисунков показано окно кода для Module1.
По мере ввода кода VBA в окно Code, редактор Visual Basic следит за правильностью ввода, ищет ошибки в коде и выделяет код, который требует исправления.
Окно свойств (Properties)
В окне Properties перечислены свойства объекта, который в момент создания (не в процессе выполнения программы) выделен в окне проекта. Эти свойства могут быть различными в зависимости от типа выделенного объекта (лист, книга, модуль и другие).
Окно отладчика (Immediate)
Окно Immediate можно отобразить в редакторе Visual Basic через меню View > Immediate Window или нажатием комбинации клавиш Ctrl+G. Это окно помогает при отладке кода. Оно выполняет роль области вывода для отладки выражений и позволяет вычислять отдельные выражения или выполнять строки кода по одной.
Например, введите выражение «?j» и нажмите Enter – в результате будет выведено текущее значение переменной j.
Окно переменных (Locals)
Чтобы открыть окно Locals, нажмите Locals Window в меню View редактора Visual Basic. В этом окне отображаются все переменные, объявленные в текущей процедуре. Окно делится на столбцы, в которых содержатся имя, значение и тип каждой переменной, и эта информация обновляется автоматически в ходе выполнения программы. Окно Locals очень полезно при отладке кода VBA.
Окно отслеживания (Watches)
Окно Watches также очень помогает при отладке кода VBA, так как в нём можно увидеть значение, тип и контекст любого отслеживаемого выражения, которое задаст пользователь. Чтобы открыть окно Watches, нажмите Watch Window в меню View редактора Visual Basic. Также окно Watches будет открыто автоматически, если задать отслеживаемое выражение.
Чтобы задать отслеживаемое выражение, нужно:
- Выделить выражение в редактируемом коде VBA.
- В меню Debug редактора VBA нажать Quick Watch.
- Нажать Add.
Кроме рассмотренных, в меню редактора Visual Basic в Excel существует ещё множество параметров и команд, используемых при создании, выполнении и отладке кода VBA.
Оцените качество статьи. Нам важно ваше мнение: