VBScript Tutorials - Herong's Tutorial Notes
Dr. Herong Yang, Version 4.01

Procedures - Functions and Subroutines

Part:   1  2   3  4  5  6 

VB Script Tutorials - Herong's Tutorial Notes © Dr. Herong Yang

Data Types and Literals

Variables

Logic Operations

String Operations

Conditional Statements

Arrays

Loop Statements

Functions and Subroutines

Built-in Functions

Variable Inspection

... Table of Contents

(Continued from previous part...)

Function Procedure Example

To help you understand the concept of function procedure, I wrote the following the example, function_f2c.html:

<html>
<body>
<!-- function_f2c.html
   Copyright (c) 2006 by Dr. Herong Yang. http://www.herongyang.com/
-->
<pre>
<script language="vbscript">
   d = F2C(70.0)
   document.writeln("Received Celsius = " & d)
   d = F2C(212.0)
   document.writeln("Received Celsius = " & d)

Function F2C(dFahrenheit)
   document.writeln("")
   document.writeln("Converting Fahrenheit = " & dFahrenheit)
   dCelsius = (dFahrenheit - 32.0 ) / 1.8
   document.writeln("Returning Celsius = " & dCelsius)
   F2C = dCelsius
End Function
</script>
</pre>
</body>
</html>

Here is the output:


Converting Fahrenheit = 70
Returning Celsius = 21.1111111111111
Received Celsius = 21.1111111111111

Converting Fahrenheit = 212
Returning Celsius = 100
Received Celsius = 100

Easy to understand. Right?

Defining and Invoking Sub Procedures

A Sub Procedure is similar to a function procedure. It can be defined with the "Sub" statement:

   Sub sub_name(argument_list)
      statement_block
   End Sub

where "sub_name" is the name of the sub procedure (subroutine), and "argument_list" a list of variables used to pass data into and/or out of the subroutine.

Of course, "argument_list" is optional.

Notice that subroutine does not return any values.

Invoking a subroutine is different than a function procedure. You can use one of the two syntaxes below:

1. Explicit call with "Call" statement:

   Call sub_name(argument_list)

2. Explicit call with subroutine name:

   sub_name argument_list

Both syntaxes will cause the system to:

  • Stop execution in main code flow.
  • Map data or variables based on the argument list.
  • Execute the entire statement block defined inside the subroutine.
  • Continue to execute main code flow.

If you want terminate a sub procedure early, you can use the "Exit" statement:

   Exit Sub

(Continued on next part...)

Part:   1  2   3  4  5  6 

Dr. Herong Yang, updated in 2006
VBScript Tutorials - Herong's Tutorial Notes - Procedures - Functions and Subroutines