lmÉpï c£Á°npï ¸À®ÆµÀ£ï쀦 · a common mistake among new vba programmers is that...

11
iTech Analytic Solutions LmÉPï C£Á°nPï ¸À®ÆμÀ£ïì No. 9, 1st Floor, 8th Main, 9th Cross, SBM Colony, Brindavan Nagar, Mathikere, Bangalore 560 054 Email: [email protected] Website: www.itechanalytcisolutions.com Mobile: 9902058793

Upload: others

Post on 16-Oct-2020

0 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: LmÉPï C£Á°nPï ¸À®ÆµÀ£ï쀦 · A common mistake among new VBA programmers is that they put their code in the wrong module. When this happens, Excel can't find the

iTech Analytic Solutions

LmÉPï C£Á°nPï ¸À®ÆµÀ£ïì

No. 9, 1st Floor, 8th Main, 9th Cross,

SBM Colony, Brindavan Nagar, Mathikere, Bangalore – 560 054

Email: [email protected] Website: www.itechanalytcisolutions.com

Mobile: 9902058793

Page 2: LmÉPï C£Á°nPï ¸À®ÆµÀ£ï쀦 · A common mistake among new VBA programmers is that they put their code in the wrong module. When this happens, Excel can't find the

No. 9, 1st Floor, 8

th Main, 9

th Cross, SBM Colony, Brindavan Nagar, Mathikere, Bangalore – 560 054 Page: 2

Chapter 6

Modules

Page 3: LmÉPï C£Á°nPï ¸À®ÆµÀ£ï쀦 · A common mistake among new VBA programmers is that they put their code in the wrong module. When this happens, Excel can't find the

No. 9, 1st Floor, 8

th Main, 9

th Cross, SBM Colony, Brindavan Nagar, Mathikere, Bangalore – 560 054 Page: 3

What is a Module?

VBA code is typed in the VBA Editor in what are called modules

A VBA module resembles a Word document in both organization and typing

You type commands in these modules then run them to control Microsoft Excel

The VBA modules themselves are organized in what is called a VBA project

A VBA project is defined as a collection of VBA modules and other programming elements

When a new workbook file is created in Microsoft Excel, a new VBA project is automatically created and

associated with that workbook

A workbook can contain only 1 VBA project

You add VBA modules, code and other elements to a VBA project when you need them

You run your macros from the workbook they were created in. You need the workbook open in Excel to

run its code

Different Types of Modules

A common mistake among new VBA programmers is that they put their code in the wrong module. When

this happens, Excel can't find the code, and it can't be executed. So codes should be written in appropriate

Modules. Following are the different types of Modules where you write the VBA codes

Standard Module

Standard Module can contain code to do almost anything of a „general purpose‟ nature. Examples of code

that might appear in them would be code that responds to shapes or command buttons you might put on a

worksheet; code to respond to custom menus you might develop, user defined functions (UDF) that you

develop to perform actions and calculations by way of using the name of the UDF in a worksheet formula just

like a built-in Excel worksheet function.

All Macros you record are placed into general purpose modules. Recording macros during different sessions

with the workbook results in numerous modules that may contain as few as a single procedure (macro) in it.

This results in being quite wasteful of resources. All macros recorded during a single session are typically

placed into a single module.

To create a new general purpose module you can use the Insert Module option from the VBE menu

toolbar

Page 4: LmÉPï C£Á°nPï ¸À®ÆµÀ£ï쀦 · A common mistake among new VBA programmers is that they put their code in the wrong module. When this happens, Excel can't find the

No. 9, 1st Floor, 8

th Main, 9

th Cross, SBM Colony, Brindavan Nagar, Mathikere, Bangalore – 560 054 Page: 4

Or

Right Click on the Project Explorer, Select Insert Module

After inserting the first new general purpose module, you‟ll have a new entry in the VBAProject window.

Now you have a new collection called Modules and the new module you just created will be listed as one of

the members of the collection. Any more modules you add will be listed as new members of the collection.

You can double-click on any of them and view its contents in the Code Window.

The one property that a module has is its Name. You can give more meaningful names than just “Module1” or

“Module2” by changing the name in the properties window while the module is the current or active object.

There‟s no rule for naming modules except that they must start with an alpha character and can't contain

certain special characters, I like to give mine names that start with “mod” (for MODULE) followed by some

description of the use of the code within them. Examples might be names like:

mod_Utilities

Page 5: LmÉPï C£Á°nPï ¸À®ÆµÀ£ï쀦 · A common mistake among new VBA programmers is that they put their code in the wrong module. When this happens, Excel can't find the

No. 9, 1st Floor, 8

th Main, 9

th Cross, SBM Colony, Brindavan Nagar, Mathikere, Bangalore – 560 054 Page: 5

mod_Declarations

mod_Product_Info

While there is no practical (or published) limit to the number of modules, I‟m sure it‟s at least one of those

“limited by available memory” things. The maximum size of any individual module is 64K (to the best of my

recollection). You can put a LOT of code into a single module.

Workbook Modules

There is one and only one code module per workbook that is associated with Workbook Event handling. At

the technical level, this module, along with the worksheet event handling modules are Class Modules. That

need not concern you. Just be aware that if you want to do any coding that deals with events that occur

at the workbook level, you do it in Workbook module.

Workbook Events

Just what are the workbook events? You can get a complete list of them from the code window while the

Workbook Code module content is displayed: You can display that content by double-clicking the

ThisWorkbook object in the VBAProject window. You‟ll get a display similar to this

If you use the left pulldown of the workbook‟s code module you‟ll see that there is a specific Workbook entry.

If you choose that item, the VBE will automatically insert a stub (just the beginning declaration and end

statement for the procedure) for the Workbook_Open() event. You can delete that entry if you don‟t need

code to deal with something you want to happen when the workbook is opened.

With your cursor placed inside of any Workbook related procedure, even just a stub, you can then use the

pulldown on the right to find a list of all the available event handlers for the workbook. And it is quite a list.

NOTE: If the cursor is not in a workbook event handling procedure, the list on the right will show you a list of

non-workbook event procedure names in the module.

If you write code inside any of the event procedure, then when that event is triggered the code associated

with that event will run; i.e., the code will execute. Some typical Workbook associated events that are often

provided with code are:

Workbook_Open()

Workbook_Close()

Workbook_BeforeClose()

Page 6: LmÉPï C£Á°nPï ¸À®ÆµÀ£ï쀦 · A common mistake among new VBA programmers is that they put their code in the wrong module. When this happens, Excel can't find the

No. 9, 1st Floor, 8

th Main, 9

th Cross, SBM Colony, Brindavan Nagar, Mathikere, Bangalore – 560 054 Page: 6

Workbook_BeforePrint()

Workbook_BeforeSave()

Workbook_Activate()

Workbook_Deactivate

Things you might do with some of these? Well, in the Open() event you might make certain that a particular

worksheet is the one selected so that the user sees it first. Or with BeforeSave() or BeforeClose() you might

examine certain cells to make sure that all required information had been entered into the workbook and even

that it falls within acceptable limits. Activate and/or Deactivate? These are great for determining when to

create/destroy custom menus to be used in the workbook but that you don‟t want available in other

workbooks.

Worksheet Modules

There is one and only one code module per worksheet that is associated with Worksheet Event handling.

However, each sheet has its very own code module that is separate and distinct from all of the others even

though they may all have event handlers for a given event for those worksheets. At the technical level, this

module, just like the event handling module for the workbook are Class Modules. Remember that if you

want to do any coding that deals with events that occur at the worksheet level, you do it in these

modules.

Worksheet Events

Just what are the worksheet events? You can get a complete list of them from the code window while any

Worksheet Code module content is displayed: You can display that content by double-clicking any worksheet

object in the VBAProject window. The code module for that sheet will be displayed. You‟ll get a display similar

to this

For worksheets, when you choose the Worksheet item in the left pulldown list, the default event is the

Worksheet_SelectionChange(ByVal Target As Range) event. This even triggers any time you make a new

selection on the sheet – such as simply moving to another cell. The new cell becomes the selection, and thus

you‟ve had a selection change.

As with the Workbook events, you can now get a complete list of Worksheet Events available to be

programmed against by using the right-side pulldown (indicated by “(Declarations)” in the graphic). This list is

much shorter than the Workbook‟s list, but even these 9 (from Excel 2003) provide considerable versatility in

dealing with worksheets. Out of the list, the Change() event is probably the one that most often has code

Page 7: LmÉPï C£Á°nPï ¸À®ÆµÀ£ï쀦 · A common mistake among new VBA programmers is that they put their code in the wrong module. When this happens, Excel can't find the

No. 9, 1st Floor, 8

th Main, 9

th Cross, SBM Colony, Brindavan Nagar, Mathikere, Bangalore – 560 054 Page: 7

associated with it. A Change() occurs when a user alters the contents (value) of one or more cells on the

sheet. Worksheet formula recalculations don‟t trigger this event, but they do trigger the Calculate() event.

The ‘Target’ and ‘Cancel’ Objects

Often in worksheet event stubs provided by the VBE you will see reference to two special objects (sometimes

more or others also): Cancel and/or Target.

Target represents the Range [which is an object that represents a single cell, a group of cells, one or more

rows and/or one or more columns] that is active at the time the event took place. Think of Target as the actual

object itself. Anything you do to Target is done to the actual Range that it represents. Changes made to

Target will appear on the sheet itself.

The Cancel object is a Boolean type object. A Boolean object can only have one of two conditions assigned

to it: TRUE or FALSE. By default a Boolean object is FALSE (and has a numeric value of zero). If your code

sets Cancel = TRUE then the underlying event action is cancelled: the DoubleClick never takes place or the

RightClick never gets completed. These are handy events to use to take very special actions with – you can

have someone double-click in a cell (and set Cancel = True) to begin a series of events unique to that cell. A

real world example of this type of thing in one application I developed is that in a data area matrix that has

dates in the top row, a double-click on a date causes all rows with an empty cell in that column to become

hidden: a kind of auto filter based on empty cells for that one column.

Page 8: LmÉPï C£Á°nPï ¸À®ÆµÀ£ï쀦 · A common mistake among new VBA programmers is that they put their code in the wrong module. When this happens, Excel can't find the

No. 9, 1st Floor, 8

th Main, 9

th Cross, SBM Colony, Brindavan Nagar, Mathikere, Bangalore – 560 054 Page: 8

UserForm Module

UserForm is a customized user interface, developed in VBA. It enables a user to interact, using a Form, in an

organized and logical manner, to make data entry or for data retrieval with an Excel worksheet or to run a

VBA application. UserForm acts as a container in which you add multiple controls, each of which has a

specific use and associated properties. By itself, a UserForm will not be of much use unless controls are

added to it which are the actual user-interactive objects.

Create a UserForm

Open Visual Basic Editor (VBE) in Excel by pressing ALT+F11 in an open workbook, or right-click on the

worksheet tab at the bottom, and select View Code.

Click on View -> Project Explorer if the Project window is not visible.

Create a Userform in the Project window of the Visual Basic Editor by clicking Insert -> UserForm, and your

screen should appear as shown in Image above

If the Toolbox does not appear by itself, first check if it is not hidden by clicking on the UserForm (or double-

clicking on UserForm name in Project Window), else click View -> Toolbox (while UserForm is selected);

Toolbox consists of Controls required for developing a VBA Application. Controls are added in the UserForm

from the Toolbox, in the Visual Basic Editor.

If the Properties Window is not visible, click on View -> Properties Window. On clicking the UserForm in the

Project Explorer, you can view and change the properties of the UserForm in the Properties Window. Each

Page 9: LmÉPï C£Á°nPï ¸À®ÆµÀ£ï쀦 · A common mistake among new VBA programmers is that they put their code in the wrong module. When this happens, Excel can't find the

No. 9, 1st Floor, 8

th Main, 9

th Cross, SBM Colony, Brindavan Nagar, Mathikere, Bangalore – 560 054 Page: 9

control in the Toolbox such as a Label or TextBox, has its own associated properties, which can be edited in

the Properties Window (ensure that the respective control is selected).

UserForm ToolBox Controls

Control Use

1 Select Object To select the controls

2 Label Stores text which is not editable by user, and is used to describe other controls.

3 TextBox Holds text by allowing user to enter or modify.

4 ComboBox Is a list of items from which a user can select, and also allows user to enter his own item in the text box. ComboBox is a combination of TextBox and ListBox.

5 ListBox Is a list of items from which a user can select, but does not allow user to enter his own item.

6 CheckBox A CheckBox whether selected or not, indicates True or False values. Used to select mutually exclusive options viz. Yes/No, On/Off, …

7 OptionButton Used to make one selection from multiple options. Also referred to as Radio Button.

8 ToggleButton Executes one action when clicked first and a different action on the second click. The button toggles bewteen the two states, On and Off.

Page 10: LmÉPï C£Á°nPï ¸À®ÆµÀ£ï쀦 · A common mistake among new VBA programmers is that they put their code in the wrong module. When this happens, Excel can't find the

No. 9, 1st Floor, 8

th Main, 9

th Cross, SBM Colony, Brindavan Nagar, Mathikere, Bangalore – 560 054 Page: 10

Control Use

9 Frame Used to group controls that work together or have some commonality. Particularly useful to group OptionButtons which become mutually exclusive within a Frame.

10 CommandButton A button, when clicked by the user, executes a code or action.

11 TabStrip Is a collection of Tabs wherein each Tab contains the same set of controls, and the content of the controls changes when a different Tab is selected.

12 MultiPage Comprises of one or more Page objects, each containing its own set of controls. Selecting a Page (ie. making it visible) hides the other Pages of the MultiPage control.

13 ScrollBar Is used to change (increment or decrement) the value displayed by other controls. The ScrollBar box can be dragged to change the control's value over larger increments.

14 SpinButton Similar to a ScrollBar, is used to increment or decrement the value displayed by other controls, without the drag facility.

15 Image Is used to display a Picture on the UserForm.

16 RefEdit Allows a user to select a worksheet range from a box, or to type in the range therein. It behaves similar to the built-in Excel reference boxes.

17 List View To create a tree structure of the List

Page 11: LmÉPï C£Á°nPï ¸À®ÆµÀ£ï쀦 · A common mistake among new VBA programmers is that they put their code in the wrong module. When this happens, Excel can't find the

No. 9, 1st Floor, 8

th Main, 9

th Cross, SBM Colony, Brindavan Nagar, Mathikere, Bangalore – 560 054 Page: 11

Class Modules

A class module is a special module in the Visual Basic Editor whose purpose is to hold VBA code

that defines classes. A class module looks like any other kind of module you have seen, and in

its own way acts like one, too. For example, whereas the code for worksheet event procedures

goes into worksheet modules, the code for creating and defining classes goes into class

modules.

You create a class module in the VBE by clicking Insert Class Module from the menu bar as

shown below.

A class module is created with the default name of Class1 as shown in below: