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.
How to pass values in to a Sub or Function
To pass values in to subroutines or functions simply specify them in between the parenthesis of the function you are calling. Passing values to subroutines and functions works the same way for both. An example of the syntax is:
NameOfFunction(parameter1, parameter2)
or
CheckForChar(eaddress, "@")
You can pass values to functions by reference or by passing the value explicitly. To pass a value by reference simply pass in the name of the variable.
Example:
MyFunction(VarName1)
Or you can pass in the value explicitly, like this:
MyFunction("Brinkster")