VBScript – What is a Function?

--> (Word) --> (PDF) --> (Epub) --> (Text)
--> (XML) --> (OpenOffice) --> (XPS)

VBScript functions are self contained blocks of code that perform a given "function", or task.

Sometimes when coding, you may find yourself having to write the same piece of code over and over again. If this happens, chances are, you'd be better off writing a function. That way, you can write the code once, then simply call the function whenever you need it.

Creating VBScript Functions

VBScript functions are defined using the Function and End Function keywords. The code that makes up the function resides between these two keywords.

Here's the method for creating VBScript functions:

  1. Start by using the Function keyword. This tells the browser that a function is about to be defined
  2. Provide a name for the [gs function] (make it concise, but descriptive)
  3. Follow the name with opening and closing brackets
  4. Add the names of any arguments that the function requires (optional)
  5. Starting on a new line, write the code that makes up the function
  6. Finish with End Function

Example:

Function sum(number1,number2)
  sum = number1 + number2
End Function

Calling VBScript Functions

A function doesn't actually do anything until it is called. Once it is called, it takes any arguments, then performs it's function (whatever that may be).

You call a VBScript function like this:

  1. Write the function name, followed by opening and closing brackets;
  2. Between the brackets, provide all arguments that the function requires;

Example:

sum(100,9)

Combined - Creating, then Calling a VBScript Function

So, if we combine them together, and add a tiny bit more code, we might end up with something that looks like this:

Function sum(number1,number2)
  sum = number1 + number2
End Function
Dim total
total = sum(100,9)
document.write(total)

Using the above code, the following is produced:

109
SOURCE

LINK (Quackit.com)

LANGUAGE
ENGLISH