unit 6: functions and subroutines - part 2/2
TRANSCRIPT
Excel Macros Level 1
Functions and Subroutines
ByRef
Sub ProcedureA()
x = 5
MsgBox x
Call AddOne(x)
MsgBox x
End Sub
Sub AddOne(ByRef i As Integer)
i = i + 1
End Sub
M. Campbell - 2010 2
p. 73
This displays 6 as x had 1 added to it by AddOne
ByVal
Sub ProcedureA()
x = 5
MsgBox x
Call AddOne(x)
MsgBox x
End Sub
Sub AddOne(ByVal i As Integer)
i = i + 1
End Sub
M. Campbell - 2010 3
p. 73
ByVal
Sub ProcedureA()
x = 5
MsgBox x
Call AddOne(x)
MsgBox x
End Sub
Sub AddOne(ByVal i As Integer)
i = i + 1
End Sub
M. Campbell - 2010 4
p. 73
Initializes x to 5
ByVal
Sub ProcedureA()
x = 5
MsgBox x
Call AddOne(x)
MsgBox x
End Sub
Sub AddOne(ByVal i As Integer)
i = i + 1
End Sub
M. Campbell - 2010 5
p. 73
Displays 5
ByVal
Sub ProcedureA()
x = 5
MsgBox x
Call AddOne(x)
MsgBox x
End Sub
Sub AddOne(ByVal i As Integer)
i = i + 1
End Sub
M. Campbell - 2010 6
p. 73
Calls AddOne and sends value of x (in this case 5)
ByVal
Sub ProcedureA()
x = 5
MsgBox x
Call AddOne(x)
MsgBox x
End Sub
Sub AddOne(ByVal i As Integer)
i = i + 1
End Sub
M. Campbell - 2010 7
p. 73
AddOne is sent the value of x only, so i is set to 5
ByVal
Sub ProcedureA()
x = 5
MsgBox x
Call AddOne(x)
MsgBox x
End Sub
Sub AddOne(ByVal i As Integer)
i = i + 1
End Sub
M. Campbell - 2010 8
p. 73
1 is added to i to get 6However, ProcedureAcannot see i
ByVal
Sub ProcedureA()
x = 5
MsgBox x
Call AddOne(x)
MsgBox x
End Sub
Sub AddOne(ByVal i As Integer)
i = i + 1
End Sub
M. Campbell - 2010 9
p. 73
This displays 5 as x was not changed by AddOne
ByRef
Pass By Reference
Allows the argument to be changed
Takes less memory and time
If not specified, VBA defaults to ByRef
ByVal
Pass By Value
Prevents the argument from being changed
Takes more memory and time
4/29/2010 M. Campbell - 2010 10
p. 75
Exiting a Procedure
To exit a function early:
Exit Function
To exit a subroutine early:
Exit Sub
4/29/2010 M. Campbell - 2010 11
p. 76