Paul The Programmer

North East Software and Websites

60 Second Blog

Lesson 10. Being Invited to Functions

Posted at 05:48 AM on December 30, 2008

In Lesson 4 I promised to talk about functions, OK then, you asked for it, here we go.

A function acts in a similar way to a bicycle messenger. We send it off with a piece of information; the information is delivered; some processing occurs; and the messenger is sent back with a reply. Unless he’s gone off for pizza or to meet a date. Our functions return results, as a variable (remember them, little boxes of goodies). Take a look at this:

 

 

Sub PutAppleInBox()

MsgBox ("There are " & AppleCount(10) & " apples in the box")

End Sub

 

Function AppleCount(intTotal As Integer) As Integer

Dim intRepeatThisLoop As Integer

Dim intBoxOfApples As Integer

 

For intRepeatThisLoop = 1 To intTotal

   intBoxOfApples = intBoxOfApples + 1

Next

 

AppleCount = intBoxOfApples

End Function

 

There’s our favourite subroutine PutAppleInBox from earlier, re-written so that there is only a MsgBox in the to do list.  The MsgBox contains the messenger function “AppleCount”, which is being asked to go off and calculate the number of apples then, bring back the result.

 

AppleCount is the function, we pass in a variable (in this case an integer called intTotal) and the messenger function uses this variable to carry out its own to do list of instructions. Once complete the function passes back the resulting variable, in this case As an Integer.

 

Functions and subroutines can be as complex or simple as you want to make them. But, by splitting down a longer program into a series of subs and functions you ensure you’ve left yourself lots of bug hunting and code-re-writing for weeks years to come!

 

Categories: VBA Tutorials (mixed nuts)

Post a Comment

Already a member? Sign In

0 Comments

Dont Miss a thing.

Get FREE updates from me by email. Get a mini profile that lives on my website. Learn and teach. Communicate and share ideas with other members. Join here.

Recent Blog Entries

by paultheprogrammer | 0 comments
by paultheprogrammer | 1 comments
by paultheprogrammer | 0 comments
by paultheprogrammer | 2 comments

Recent Forum Posts

by paultheprogrammer over a year ago

Recent Videos