- The Fundamentals of VBScript
- VBScript Versus VB
- Creating Variables in VBScript
- Concatenating Strings
- Arrays and Loops
- Resizing Arrays
- Inequality Operators
- Conditional Statements
- Select Case Statements
- Sub
- Function
- Working with Arguments
- Beware of Types
- Event Procedure Naming Syntax
- Server-Side Events
- Local Variables
- Script-Level Variables
Sub
A Sub is a procedure that executes the statements within its code block, but does not return a value when execution is complete. You create a Sub using the following syntax:
<SCRIPT LANGUAGE=VBScript> Sub SubName() ...statements End Sub </SCRIPT>
Where Sub and End Sub are VBScript keywords. SubName is a user-defined name of the procedure. Parentheses are required following the SubName.
You've seen Sub throughout this chapter, in the guise of the OnClick() event procedure. (Event procedures are special Subs that you'll learn about later in this chapter.)
Listing 3.10 shows an example of a Sub, GetBiggerNumber(), which is called from another Sub, button1_OnClick(). Please notice that the Call <keyword> is used within the event procedure button1_OnClick() to execute the Sub, GetBiggerNumber(). The Call <keyword> , although optional to use to execute a Sub, is a good tool to use. It allows anyone viewing your code to see that a Sub rather than a variable is being accessed. For the most part, the order in which Subs are written is irrelevant in terms of precedent of execution (see Listing 3.10) .
Listing 3.10: A Simple Sub (03asp10.htm)
<HTML> <HEAD> <TITLE></TITLE> </HEAD> <SCRIPT LANGUAGE=VBScript> Sub GetBiggerNumber() Dim x Dim y 'Get the First Number x = Cint(text1.value) 'Get the Second Number y = Cint(text2.value) If x > y Then text3.value = x Else text3.value = y End If End Sub Sub button1_OnClick() Call GetBiggerNumber End Sub </SCRIPT> <BODY> <P>First Number: <INPUT name=text1 size=15></P> <P>Second Number: <INPUT name=text2 size=15></P> <INPUT type="button" value="Get Bigger Number" name=button1> <P>Bigger Number: <INPUT name=text3 size=15></P> </BODY> </HTML>
Figure 3.8 displays the output of the code in Listing 3.10.
Figure 3.8 Using a Sub promotes code reusability.