Datasheet

Chapter 1: A Quick Introduction to Programming
21
Turning Code into a Function
Some of the code that follows is from an example you used earlier in the chapter. Here’s how to turn
code into a function.
Function PromptUserName
‘ This Function prompts the user for his or her name.
‘ If the user enters nothing it returns a zero-length string.
‘ It incorporates various greetings depending on input by the user.
Dim YourName
Dim Greeting
YourName = InputBox(“Hello! What is your name?”)
If YourName = “” Then
Greeting = “OK. You don’t want to tell me your name.”
ElseIf YourName = “abc” Then
Greeting = “That’s not a real name.”
ElseIf YourName = “xxx” Then
Greeting = “That’s not a real name.”
Else
Greeting = “Hello, “ & YourName & “, great to meet you.”
If YourName = “Fred” Then
Greeting = Greeting & “ Nice to see you Fred.”
End If
End If
MsgBox Greeting
PromptUserName = YourName
End Function
The first things to take note of in the code are the first and last lines. While not groundbreaking, these are
what define a function. The first line defines the beginning of the function and gives it a name while the
last line defines the end of the function. Based on the earlier discussion of code blocks, this should
be a familiar convention by now. From this, you should begin to realize that a procedure is nothing but
a special kind of code block. The code has to tell the script engine where it begins and where it ends.
Notice also that you’ve given the function a clear, useful name that precisely describes what this function
does. Giving your procedures good names is one of the keys to writing programs that are easy to read
and maintain.
Notice also how there’s a comment to the beginning of the procedure to describe only what it does, not
how the function does what it does. The code that uses this function does not care how the function
accomplishes its task; it only cares about inputs, outputs, and predictability. It is vitally important that
you add clear, informative comments such as this to the beginning of your procedures, because they
make it easy to determine what the function does. The comment also performs one other valuable ser-
vice to you and any other developer who wants to call this function — it says that the function may
return a zero-length string if the user does not enter his or her name.
c01.indd 21c01.indd 21 8/27/07 7:45:25 PM8/27/07 7:45:25 PM