unit 6: functions and subroutines - part 2/2

11

Click here to load reader

Upload: matthew-campbell

Post on 03-Jul-2015

580 views

Category:

Education


2 download

TRANSCRIPT

Page 1: Unit 6: Functions and Subroutines - Part 2/2

Excel Macros Level 1

Functions and Subroutines

Page 2: Unit 6: Functions and Subroutines - Part 2/2

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

Page 3: Unit 6: Functions and Subroutines - Part 2/2

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

Page 4: Unit 6: Functions and Subroutines - Part 2/2

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

Page 5: Unit 6: Functions and Subroutines - Part 2/2

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

Page 6: Unit 6: Functions and Subroutines - Part 2/2

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)

Page 7: Unit 6: Functions and Subroutines - Part 2/2

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

Page 8: Unit 6: Functions and Subroutines - Part 2/2

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

Page 9: Unit 6: Functions and Subroutines - Part 2/2

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

Page 10: Unit 6: Functions and Subroutines - Part 2/2

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

Page 11: Unit 6: Functions and Subroutines - Part 2/2

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