Professional Documents
Culture Documents
033 VBA Subs
033 VBA Subs
Procedures
Functions
Executing a Sub
Create and Edit VBA Subs
Understand the difference between VBA
procedures and functions
Understand VBA procedure subs
Understand VBA function subs
Understand how VBA subs are executed
A unit of programming code that is used to
perform some action
◦ One or more subs in a VBA module
◦ Created by:
Recording a macro
Manually creating a macro
Select Procedure from the Insert Menu of the VBE
Give the sub a name
Select Procedure or Function
Select Public or Private (usually Public)
Click OK
A unit of programming code that is used to
perform some action
◦ Named using rules similar to naming variables
Function subs cannot have a name that looks like a cell
address (i.e. A23) so that Excel will not confuse the
sub name with a reference to a cell.
◦ May include one or more parameters
A VBA sub that performs a task, but does not
return a value to the caller
Sub selectionLocation()
' This sub displays the row and column of upper left corner of the
current selection in a message box
End Sub
A VBA Sub that performs some calculation(s) and
returns a result to the caller
Value is returned by ‘assigning’ a value to the
function name
End Function
Running a sub procedure directly from the
VBE
◦ Press F5 key or
◦ Choose Run Sub/UserForm from Run Menu or
◦ Choose run from the Macro dialog box
Using a shortcut key
◦ Define a shortcut key for a sub using the options
button on the Macro dialog box
◦ Click the shortcut key to execute the procedure
◦ Be careful what shortcuts you assign as they
override Excel shortcuts (i.e. ctrl-c)
From another Sub
◦ ‘Call’ subname
Sub mainSub()
Call selectionLocation()
End Sub
From a spreadsheet cell formula
Calling it from another sub
Calling it from the Immediate Window
From a spreadsheet cell formula
◦ i.e.
Formula for cell c5:
= sayHi()
Formula will place the returned value into the cell C5
Calling from another sub
Sub mainSub()
Dim functionResponse as String
functionResponse = sayHi()
End Sub
Calling from the Immediate Window
Type ? Followed by the function name
◦ The ? Instructs VBA to execute the function
?sayHi()