Print

User Rating: 4 / 5

Star ActiveStar ActiveStar ActiveStar ActiveStar Inactive
 

 

Excel VBA: Calling Sub Procedures & Functions, Placement in Modules

 

--------------------------------------------------------------------------------

Contents:

Sub procedures, Function Procedures & Property Procedures

Naming Rules & Conventions for Procedures

VBA Procedures Scope - Public vs Private

Placement of Macros / Sub procedures in appropriate Modules

Calling Procedures

Executing Procedures

-------------------------------------------------------------------------------- 

 


 

Sub procedures, Function Procedures & Property Procedures

 

A VBA project can contain multiple modules, class modules and user forms. Each module contains one or more procedures viz. sub-procedures or functions. Procedures break a program into smaller and specific components. A VBA procedure, also referred to as a Macro, is defined as a set of codes which make Excel perform an action. A procedure is usually of two types, a sub procedure or a function. The third type of procedure is Property, used for Class Modules. As explained below in detail: sub-procedures do not return a value; functions return a value; property procedures are used to return and assign values, and set a reference to an object.

 

Sub procedures

 

Event Procedures - are predefined by VBA:

 

One category of sub procedures are Event Procedures which are triggered by a predefined event and are installed within Excel having a standard & predetermined name viz. like the Worksheet change procedure is installed with the worksheet - "Private Sub Worksheet_Change(ByVal Target As Range)", which combines the object name, underscore, and the event name. The other category of sub-procedures are those which are created by the user. For a detailed understanding of Event Procedures, refer our section: Excel VBA Events, Event Procedures (Handlers), Triggering a VBA Macro.

 

 

User Created Sub procedures:

 

Creating a sub procedure: A sub procedure declaration statement starts with the keyword Sub, followed by a name and then followed by a set of parentheses. A sub-procedure ends with an End Sub statement which can be typed but it also appears automatically on going to the next line after the Sub declaration statement is typed. Your vba code or statements are entered inbetween. See below example of a procedure named Greetings, running or executing which will return the message Welcome:

 

Sub Greetings()


MsgBox "Welcome!"


End Sub

 

 

 

Function Procedures

 

A sub-procedure is a set of vba codes or statements which perform an action, but does not "return a value". A Function is also used to perform an action or calculation (which can also be performed by a sub procedure) but "returns a value", which is a single value. The name of the function can be used within the function procedure to indicate the value returned by the function - refer Example 4 which shows the variance between how a function and sub works. Like you use built-in Excel functions of SUM, MAX, MIN, COUNT, AVERAGE, etc., Function procedures are created in vba to make custom worksheet functions. Function procedure cannot be created using a Macro Recorder. A sub procedure uses a different syntax as compared to a Function. A Function procedure can be called by using its name within an expression which is not possible in respect of a sub procedure which can be called only by a stand-alone statement. Because a function returns a value, it can be used directly in a worksheet (which is not possible with a sub-procedure), by entering/selecting the name of the function after typing an equal sign (refer Image 1).

 

Creating a Function procedure: A function declaration statement starts with the keyword Function, followed by a name and then followed by a set of parentheses. You must specify the data type which is the type of value the function will return - this is done by typing the keyword As (after the parentheses) followed by the data type. Functions can be created without arguments or with any number of arguments which are listed between the parentheses and in case of multiple arguments, separate them with commas. A function procedure ends with an End Function statement which can be typed but it also appears automatically on going to the next line after the Function declaration statement is typed. Your vba code or statements are entered inbetween the Function declaration statement & the End statement.

 

Executing a Function procedure: (i) the function can be called from another procedure viz. a sub-procedure or function procedure; and (ii) the function can be used directly in the spreadsheet viz. in a worksheet formula by entering/selecting the name of the function after typing an equal sign. See below examples of Function procedures and how they are called:

 

 

Example 1

 

Function partNames() As String
'The declaration of the partNames function contains no argument.


Dim strFirstName As String
Dim strSurName As String

strFirstName = InputBox("Enter first name")
strSurName = InputBox("Enter sur name")

partNames = strFirstName & " " & strSurName


End Function

 

 

Sub fullName()


'call the partNames function and place value in cell A1 of active sheet:
ActiveSheet.Range("A1") = partNames


End Sub

 

 

Example 2

 

Function cubeRoot() As Double
'The declaration of the cubeRoot function contains no argument.


Dim i As Integer

i = InputBox("Enter an Integer")
cubeRoot = i ^ (1 / 3)
cubeRoot = Format(cubeRoot, "#.##")


End Function

 

 

Sub callCubeRoot()


'call the cubeRoot function in the message box:
MsgBox "Cube Root of the number is " & cubeRoot


End Sub

 

 

 

Example 3 (refer section on Passing Arguments to Procedures, Excel VBA to understand how arguments are passed in a procedure)

 

Function triple(i As Integer) As Long
'The declaration of the triple function contains one variable as argument.


triple = i * 3


End Function

 

 

Sub integerTriple()


Dim a As Integer

a = InputBox("Enter an Integer")

'call the triple function:
MsgBox triple(a)


End Sub

 

Refer Image 1 which displays how the function is used in a worksheet.

 

 

It may be noted that the set of parentheses, after the procedure name in the Sub or Function declaration statement, is usually empty. This is the case when the sub procedure or Function does not receive arguments. However, when arguments are passed to a sub procedure or a Function from other procedures, then these are listed between the parentheses.

Refer section on Passing Arguments to Procedures, Excel VBA to understand how arguments are passed in a procedure.

 

 

Example 4: shows the variance between how a function and sub works - functions return a value whereas sub-procedures do not return a value.

 

For live code, click to download excel file.

 

The addSquare function returns a value which can be used by the calling procedure:

 

Function addSquare() As Double
'the addSquare function returns a value in its own name:


Dim a As Double
Dim b As Double

a = InputBox("Enter first number")
b = InputBox("Enter second number")

addSquare = (a + b) ^ 2


End Function

 

 

Sub calculate()
'This is the calling procedure: calls the addSquare function.


Dim c As Double

'the addSquare function returns a value which can be used by the calling procedure:
c = addSquare ^ (1 / 2)
MsgBox c


End Sub

 

 

The addSquare1 sub-procedure does NOT return a value which can be used by the calling procedure:

 

Sub addSquare1()


Dim a As Double
Dim b As Double
Dim c As Double

a = InputBox("Enter first number")
b = InputBox("Enter second number")

c = (a + b) ^ 2
MsgBox c


End Sub

 

 

Sub calculate1()
'This is the calling procedure: calls the addSquare1 sub procedure.


'the addSquare1 sub-procedure does NOT return a value which can be used by the calling procedure. The calling procedure (calculate1) can only call the addSquare1 sub-procedure without being able to use its result:
addSquare1


End Sub

 

 

 

Property Procedures

 

For a detailed understanding of Property Procedures, refer section Custom Classes & Objects, Custom Events, using Class Modules in Excel VBA.

 

Property Procedure is a set of vba codes that creates and manipulates custom properties for a class module. The properties of the class object are manipulated in a Class Module with Property procedures which use the Property Let, Property Get, and Property Set statements. A Property procedure is declared by a Property Let,  Property Get or Property Set statement and ends with an End Property statement. Property Let (write-only property) is used to assign a value to a property and Property Get (read-only property - which can only be returned but not set) returns or retrieves the value of a property. Property Set (write-only property) is used to set a reference to an object. Property procedures are usually defined in pairs, Property Let and Property Get OR Property Set and Property Get. A Property Let procedure is created to allow the user to change or set the value of a property, whereas the user cannot set or change the value of a read-only property (viz. Property Get).

 

A property procedure can do whatever can be done within a vba procedure like performing an action or calculation on data. A Property Let (or Property Set) procedure is an independent procedure which can pass arguments, perform actions as per a set of codes and change the value of its arguments like a Property Get procedure or a Function but does not return a value like them. A Property Get procedure is also an independent procedure which can pass arguments, perform actions as per a set of codes and change the value of its arguments like a Property Let (or Property Set) procedure, and can be used similar to a Function to return the value of a property.

 

The Property Set procedure is similar to and a variation of the Property Let procedure and both are used to set values. A Property Set procedure is used to create object properties which are actually pointers to other objects, whereas a Property Let procedure sets or assigns values to scalar properties like string, integer, date, etc. Using the Property Set statement enables Properties to be represented as objects.

 

 


 

 

Naming Rules & Conventions for Procedures

 

It will help to assign a procedure name which is reflective of the action you wish to perform with the procedure. Some programmers prefer to use a sentence, differentiating words by an underscore or a capital letter viz. total_number_of_rows, TotalNumberOfRows. Use of very lengthy names names is generally avoidable.

 

There are some rules which are to be followed when naming your procedures:

 

The name must begin with a letter, and not a number or underscore.

 

A name can consist of letters, numbers or underscores but cannot have a period (.) or punctuation characters or special characters (such as ! @ # $ % ^ & * ( ) + - = [ ] { } ; ' : " , . / < > ? \ | ` ~).

 

The name should consist of a string of continuous characters, with no intervening space.

 

A procedure name can have a maximum of 255 characters.

 

Procedure names cannot use keywords / reserved words such as If, And, Or, Loop, Do, Len, Close, Date, ElseIf, Else, Select, ... that VBA uses as part of its programming language.

 

 

Valid Names:

TotalRows

total_rows_10

Total_number_of_Rows

 

Invalid Names: 

Total.Rows

5Rows

Total&Rows

Total Rows (space not allowed)

 

 

 


 

 

VBA Procedures Scope - Public vs Private

 

A vba procedure can have either Public or Private Scope. A procedure can be specified as such by preceding it with the Public or Private keyword. Procedures are Public by default, if the Public keyword is not specified.

 

A Private procedure can only be called by all procedures in the same module and will not be visible or accessible to procedures of outside modules in the project. A Private procedure will also not appear in the Macros dialog box. A

Public procedure can be called by all procedures in the same module and also by all procedures of outside modules in the project. A Public procedure's name will appear in the Macros dialog box and can be run therefrom.

 

Creating a Public procedure:

Sub calculateProcedure()

Public Sub calculateProcedure()

Function cubeRoot() As Double

Public Function cubeRoot() As Double

 

Creating a Private procedure:

Private Sub calculate()

Private Function cubeRoot() As Double

 

 

 


 

 

Placement of Macros / Sub procedures in appropriate Modules

 

Macros (viz. vba codes or sub-procedures) should reside in their appropriate modules or Excel will not be able to find and execute them. The Object Modules are used for Excel built-in event procedures and to create your own events. Object Modules in Excel are: ThisWorkbook module, Sheet modules (worksheets and chart sheets), UserForm modules and Class modules. General vba code in respect of events not associated with a particular object (like workbook or worksheet) are placed in the standard code module. A generally accepted practice is to place event procedures in the ThisWorkbook module, Sheet modules and UserForm modules, while placing other vba codes in Standard Code modules.

 

Refer Image 2 which shows the Modules in VBE.

 

 

Standard Code Modules:

 

These are also referred to as Code Modules or Modules, and there can be any number of these Modules (Module1, Module2, …) in a VBA project, wherein each Module can be used for covering a certain aspect of the project. Most vba codes and custom functions (viz. User Defined Functions referred to as UDFs) are placed in Standard Code Modules. Standard Code Modules are not used for event procedures linked and associated to a Workbook or Worksheet or UserForm or for Application events created in a Dedicated Class Module. In respect of events not associated with objects, such as OnTime method (automatically trigger a vba code at periodic intervals or at a specific day or time) and OnKey method (run a specific code on pressing a key or combination of keys), because these are not associated with a particular object like workbook or worksheet, their codes rest in the standard code module. Procedures in standard modules can be called from a procedure in an outside module just like you call a procedure located in the same module ie. without specifying the module of the called procedure.

 

 

Workbook module:

 

ThisWorkbook is the name of the module for the workbook and is used to place workbook events and Application Events. Workbook events are actions associated with the workbook, to trigger a VBA code or macro. Opening / closing / saving / activating / deactivating the workbook are examples of workbook events viz. with a workbook open event, you can run a sub-procedure automatically when a workbook is opened. Workbook events code must be placed in the code module for the ThisWorkbook object, and if they are placed in standard code modules, Excel will not be able to find and execute them. Though Application Events can be created in any object module, they are best placed in either an existing object module like ThisWorkbook or you can create a class module to handle them. Though general vba codes and procedures can also be placed in a workbook, but you will need to include 'ThisWorkbook' in the reference to call them (from outside the workbook module) viz. ThisWorkbook.ProcedureName.

 

 

Sheet Modules:

 

A sheet module has the same name as the worksheet's code name with which it is associated viz. Sheet1, Sheet2, … In VBE, the code name of the selected worksheet appears to the right of (Name) in the Properties Window while the sheet name appears to the right of Name when you scroll down in the Properties Window. The code name can be changed only in the Properties window and not programmatically with code. Sheet module can be for a worksheet or a chart sheet  and is used to place worksheet and chart sheet events. Worksheet events are actions or occurrences associated with the worksheet, to trigger a VBA code or macro. Chart sheet events (ie. if a chart is a chart sheet) reside within its chart sheet and are enabled by default, similar to as worksheet events reside in their worksheet. But for using events for a chart object representing an embedded chart in a worksheet, a new class module has to be created.

 

To use the Excel provided worksheet event procedures, in the Visual Basic Editor after selecting the appropriate worksheet, select Worksheet from the Object box and then select a corresponding procedure from the Procedure box. After selecting the specific event, insert the vba code you want to be executed. Worksheet Event procedures are installed with the worksheet, ie. the code must be placed in the code module of the appropriate Sheet object and if they are placed in standard code modules, Excel will not be able to find and execute them. Instances of worksheet events are: selecting a cell or changing cell selection in a worksheet, making a change in the content of a worksheet cell, selecting or activating a worksheet, when a worksheet is calculated, and so on. For example, with the worskheet change event, a sub-procedure runs automatically when you change the contents of a worksheet cell. Though general vba codes and procedures can also be placed in a worksheet, but you will need to include the sheet module name in the reference to call them (from outside that sheet module) viz. Sheet3.ProcedureName.

 

 

UserForm Modules:

 

Event procedures for UserForm or its Controls are placed in the Code module of the appropriate UserForm. UserForm events are pre-determined events that occur for a particular UserForm and its Controls, examples include Initialize, Activate or Click. These are placed in the user form code module. You must double-click the body of a UserForm to view the UserForm Code module, referred to as a module 'behind' the UserForm, and then select UserForm or its Control from the Object box and then select a corresponding procedure from the Procedure box. After selecting the specific event, insert the vba code you want to be executed. Remember to set the Name property of controls before you start using event procedures for them, else you will need to change the procedure name corresponding to the control name given later. Only event procedures for the UserForm or its controls should be placed here. However, general vba codes and procedures can also be placed in a UserForm, but you will need to include the UserForm module name in the reference to call them (from outside that UserForm module) viz. UserForm1.ProcedureName.

 

 

Class Modules:

 

Class Modules are used to create new objects and you can create your own custom events in a class. A Custom Event is defined and declared in a Class Module using the Event keyword. An Event procedure can be created using the WithEvents keyword to declare an object variable of the Class Module type. Though Application Events can be created in any object module, they are best placed in either an existing object module like ThisWorkbook or by creating a class module to handle them. Also, for using events for a chart object representing an embedded chart in a worksheet, a new class module has to be created.

 

For a detailed understanding of Class Modules, refer section Custom Classes & Objects, Custom Events, using Class Modules in Excel VBA.

 

 

 


 

 

Calling Procedures

 

Subs and Functions can be called within each other. Calling a procedure refers to using or executing a procedure.

 

 

Calling Sub procedures in the Same Module

 

You can call sub-procedures either solely by their name or precede the name with the Call keyword.

 

Calling a sub named strGetName which does not receive arguments, which was declared as - Sub strGetName():

strGetName

Call strGetName

 

Calling a sub named strGetName which receives arguments, which was declared as - Sub strGetName(firstName As String, secondName As String):

Call strGetName(firstName, secondName)

strGetName firstName, secondName

 

Note that argument(s) must be enclosed within parentheses when using the Call keyword, and multiple arguments must omit the parentheses when the Call keyword is not used.

 

 

 

Calling Functions in the Same Module

 

Functions can be called in a manner similar to Subs and can also be used in an expression by their name. Functions can also be used directly in a worksheet, by entering/selecting the name of the function after typing an equal sign (refer Image 1 for using the Example 3 function in a worksheet). 

 

A function declared as - Function studentNames() As String - can be called as below:

studentNames

Call studentNames

 

A function which receives arguments and declared as - Function triple(i As Integer, j As Integer) As Long - can be called as below:

Call triple(i, j)

triple i, j

 

Using a Function in an expression: A function declared as - Function cubeRoot() As Double - can be called as below:

MsgBox cubeRoot * 2

 

 

 

Calling Procedures in Outside Modules

 

As explained above, Public procedures can be called by all procedures of outside modules. To do so, it is mostly required to specify the module that contains the called procedure. There are different ways to call procedures located in a workbook/ worksheet/ form module, standard module or a class module.

 

Calling Procedures located in a Workbook Module, Worksheet Module or Forms Module

 

If the called procedure is located in a Workbook Module, Worksheet Module or Forms Module, then you will need to specify the module while calling it from an outside module.

 

A sub named strGetName, which was declared as - Sub strGetName() - and located in the workbook module named ThisWorkbook, can be called by specifying - ThisWorkbook.strGetName - in the calling procedure located in an outside module.

 

A sub named strGetName, which was declared as - Sub strGetName() - and located in the worksheet module named Sheet2, can be called by specifying - Sheet2.strGetName - in the calling procedure located in an outside module.

 

A sub named strGetName, which was declared as - Sub strGetName() - and located in the UserForm named UserForm1, can be called by specifying - UserForm1.strGetName - in the calling procedure located in an outside module.

 

 

Calling Procedures located in Standard Modules

 

Procedures in standard modules can be called from a procedure in an outside module just like you call a procedure located in the same module ie. without specifying the module of the called procedure. A sub named strGetName, which was declared as - Sub strGetName() - and located in a standard module, can be called from a procedure in a worksheet module by using only its name ie. strGetName, or using the Call keyword ie. Call strGetName.

 

You might already be aware that procedures of same name are not allowed within the same module but procedures can have same names in separate modules. If both the standard modules (Module1 and Module2) have a procedure named strGetName, to call it from an outside module (say, from a standard module named Module3), you will need to specify the called procedure's module viz. Module1.strGetName OR Module2.strGetName. However, if the calling procedure is located in Module2 and if you call the procedure named strGetName without specifying the module, then the procedure strGetName located in Module 2 will be called.

 

 

Calling Procedures located in Class Modules

 

In the calling procedure located in an outside module, you need to instantiate an instance of the class in which the called procedure is located. To do this, you create a variable and definine it as a reference to the class. Use this variable with the name of the called procedure located in the class module. For example, in the calling procedure use the statement - Dim iStudent As New clsStudent - to use a variable named iStudent and create an instance of the class named clsStudent. To call the Grade function located in the clsStudent object, use the variable with the function name - iStudent.Grade. If the Grade function receives an argument, then to call the Grade function - iStudent.Grade (argument).

 

For a detailed understanding of Class Modules, refer section Custom Classes & Objects, Custom Events, using Class Modules in Excel VBA.

 

 

 


 

 

Executing Procedures

 

Executing Function Procedures:

 

Executing a Function procedure: (i) the function can be called from another procedure viz. a sub procedure or function procedure; and (ii) the function can be used directly in the spreadsheet viz. in a worksheet formula by entering/selecting the name of the function after typing an equal sign. To see examples of Function procedures and how they are called, refer the headings "Function Procedures"  & "Calling Procedures" hereinabove.

 

 

Executing Event Procedures:

 

Events are actions performed, or occurrences, which trigger a VBA macro. An event procedure (ie. a vba code) is triggered when an event occurs such as opening / closing / saving / activating / deactivating the workbook, selecting a cell or changing cell selection in a worksheet, making a change in the content of a worksheet cell, selecting or activating a worksheet, when a worksheet is calculated, and so on.

 

Event procedures are attached to objects: An event procedure is a procedure with a standard name that runs on the occurrence of a corresponding event. The event procedure contains the user written customized code which gets executed when the specific Excel built-in event, such as worksheet change event, is triggered. Event Procedures are triggered by a predefined event and are installed within Excel having a standard & predetermined name viz. like the Worksheet change procedure is installed with the worksheet - "Private Sub Worksheet_Change(ByVal Target As Range)". An Event Procedure is automatically invoked when an object recognizes the occurrence of an event. Event procedures are attached to objects like Workbook, Worksheet, Charts, Application, UserForms or Controls. An event procedure for an object is a combination of the object's name (as specified in the Name property), an underscore and the event name. To use the Excel provided event procedures, in the Visual Basic Editor select an object from the Object box and then select a corresponding procedure from the Procedure box. After selecting the specific event, insert the vba code you want to be executed.

 

Using ActiveX controls: ActiveX controls are used: 1) on worksheets - these can be used without or with vba code here; and 2) on UserForms, with vba code. ActiveX controls have event procedures that run on the occurrence of a corresponding event. These procedures are inserted in the code modules of the Worksheet or UserForm within which the controls are used. Some ActiveX controls can only be used on UserForms and not on worksheets. Note that you can assign macros to run directly from Forms controls, but you cannot assign a macro to run directly from ActiveX controls.

 

Using an ActiveX Control viz. Command Button, in a worksheet: On the Developer tab on the ribbon, click Insert in the Controls group, choose and click Command Button in ActiveX Controls and then click on your worksheet where you want to place the upper-left corner of the Command Button (you can move and resize later). To create an event procedure with the command button, in the code window in VBE, select the command button in the Object drop-down Box on the left, select the relevant event from the Procedure drop-down Box on the right, and insert the vba code. For example, if Click is selected in the Procedure drop-down Box after selecting CommandButton1 in the Object drop-down Box, the event procedure will be called CommandButton1_Click, and the vba code runs on clicking the Command Button.

 

Events not associated with objects, such as OnTime method (automatically trigger a vba code at periodic intervals or at a specific day or time) and OnKey method (run a specific code on pressing a key or combination of keys). Because these are not associated with a particular object like workbook or worksheet, their codes rest in the standard code module.

 

 

 

Executing Sub Procedures:

 

Run a Sub procedure (macro) using Macro dialog box, Shortcut key or in VBE:

 

Macro dialog box: Under the View tab on the ribbon, click Macros in the Macros group, click View Macros which will open the Macro dialog box. In the Macro dialog box, select the Macro name and click Run to execute the Sub/macro. You can also open the Macro dialog box by clicking on Macros in the Code group under the Developer tab on the ribbon. Yet another way is to use the key combination Alt+F8 which opens the Macro dialog box.

 

Shortcut key: Use the Shortcut key associated with the macro. For this you must already have assigned a Shortcut key to the macro which can be done both at the time when you begin recording a macro or later by selecting the sub / macro name in the macro list (in Macro dialog box) and clicking Options button.

 

Visual Basic Editor: 1) In the Visual Basic Editor, click within the sub procedure and press F5 (or click Run in the menu bar and then click Run Sub/Userform). 2) In the Visual Basic Editor, click Tools in the menu bar, then click Macros which opens the Macros dialog box. In the Macros dialog box, select the Macro name and click Run to execute the macro,

 

Obviously these methods are not very user friendly and you will not wish to automate an excel file with multiple macros and have users go through a "process" as described above, to select and run macros. A better way to run a macro would be to click on a button bearing a self-explanatory text "Calculate Bonus" appearing on the worksheet or clicking a Toolbar Button. We show how to assign a macro to an object, shape, graphic or control.

 

 

You can assign a sub / macro to:

 

A Form Control viz. Button: You can assign a macro to any Form control. On the Developer tab on the ribbon, click Insert in the Controls group, choose and click Button in Form Controls and then click on your worksheet where you want to place the the upper-left corner of the Button (you can move and resize later). Right click on the Button and select Assign Macro which opens the Assign Macro dialog box from where you can select and assign a macro to the Button.

 

The Quick Access Toolbar (Toolbar Button): Click the Office Button (top left of your excel window), click Excel Options which opens the Excel Options dialog box. Click Customize on the left, In the 'Choose commands from' drop-down box, select Macros, select a macro name on the left side list box and click 'Add' which adds it to the Quick Access Toolbar and the macro name now appears on the right side list box. To modify the macro button: select the macro name on the right side list box, click the Modify button at the bottom which opens the Modify Button dialog box from which you can select and modify the button which appears on the Quick Access Toolbar. Clicking this button on the Quick Access Toolbar will run the macro. Refer Image 3a which shows the Excel Options dialog box after selecting a macro; Image 3b shows (after clicking Add and Modify) the Modify Button dialog box wherein a new button is assigned for the macro; Image 3c (after clicking Ok twice) shows the macro button (i in blue circle) appearing on the Toolbar (we have assigned macro called macro1 in Sheet1 - Sheet1.macro1).

 

 

 

 

Any Object, Shape, Picture, Chart, Text Box, etc. inserted in the worksheet: Under the Insert tab on the ribbon, you can insert an Object, Shape, Picture, SmartArt graphic, Chart, Text Box, WordArt, etc. in the worksheet. Right click on the object, shape or graphic you have inserted, and select Assign Macro which opens the Assign Macro dialog box from where you can select and assign a macro to the Button.

 

 

Calling a Sub procedure from another Procedure:

 

Subs and Functions can be called within each other, as explained above under the heading "Calling Procedures". This means that a sub-procedure (or function) can be called from another procedure viz. a sub procedure or function procedure.

 

Assign multiple subs / macros:

 

You can assign multiple subs/macros to an object, graphic or control, by calling other sub procedures. Refer below example, in the sub procedure (CommandButton1_Click) which is executed on clicking a Command Button, two other sub procedures named macro1 and macro2 are called and executed. In this example macros are called using their names. You can view all macros by clicking Macros in the Macros group (under the View tab on the ribbon) and then selecting View Macros. Remember to type the macro names on separate lines while calling them.

 

Call sub procedures (macro1 & macro2 are located in standard code modules) using their names:

 

Private Sub CommandButton1_Click()


macro1
macro2


End Sub

 

 

Call sub procedures (using the Call method) where macro1 & macro2 are located in standard code modules and macro3 is in a worskheet module (in Sheet3) and macro4 is in the workbook module (ThisWorkbook), as shown below:

 

Private Sub CommandButton1_Click()


Call macro1
Call macro2
Call Sheet3.macro3
Call ThisWorkbook.macro4


End Sub