Go to: Articles List
First I will define the subroutine (will be referred to as a
sub from now on) and the function. Then I will give examples and
discuss when and where to use each.
Sub - A group of lines of code in a program that performs a specific
task. A sub does not return a value.
Function - A group of lines of code in a program that performs a specific
task. A function returns a value.
How to declare/write each:
Sub NameOfSubRoutine(parameter1, parameter2)
'some code...
End Sub
Example:
Sub CheckForSpaces(x)
If InStr(x," ") > 0 Then
Response.Write("Contains space(s)...")
Else
Response.Write("Does not contain space(s)...")
End If
End Function
Function NameOfFunction(parameter1, parameter2)
'some code
NameOfFunction = "return value"
End Function
NOTE: To return a value from a function, set the value you want to
return equal to the name of the function.
Example:
Function CheckForSpaces(x)
If InStr(x," ") > 0 Then
CheckForSpaces = true
Else
CheckForSpaces = false
End If
End Function
In the above examples I define a sub and function that check a
passed in string for a space. The difference between the two is that in
the sub if a space is found I write out the result and in the function
I set a variable equal to the result.
When to use each...
Sub... an example of when to use a sub over a function is when you
are just executing some code and do not want to return a value. You
might use this when you are displaying a form or running a large group
of code.
Function... an example of when to use a function over a sub is when
you want to run some code and then return back to your program the
result of the function. You might use this when you are checking to
see if a specific condition is met and need to let another part of your
program know the result.
|
|
|
|