web analytics

Subroutines and Functions in VBScript

Options

davegate 143 - 921
@2016-01-03 11:55:59

Functions and subroutines are basically smaller pieces of your script. They are generally a part that completed a specific task in the script and are very helpful in accomplishing the following:

  • Creating reusable code to use in other scripts without having to re-write the code
  • Making your code more readable
  • Helpful in debugging a script and disabling a section of code

Functions and subroutines are VERY similar. They both offer a way to better organize your code into bite sized chunks, create re-usable sections that are easier to manage and modify, and they both preform a very specific task.

But, there is only one major difference in the two of them: a subroutine does it’s work and deals with it’s result inside itself without communicating the end result back to the routine that called it to run; a function on the other hand will communicate back to the calling routine some value such as the result of some calculation or an error condition for the calling routine to process and deal with in a manner that is fitting for the situation.

The following example code shows you how to write a subroutine and a function to add two numbers together:

Sub Add(Value1, Value2)

  Dim Sum
  Sum = value1 + Value2
  WScript.Echo Value1 & ” + ” & Value2 & ” = ” & Sum
End Sub

Function Add(Value1, Value2)
  Dim Sum
  Sum = value1 + Value2
  
  Add = Sum

End Function
@2016-01-03 11:58:52

Calling a Subroutine

To call a subroutine in vbscript, you can use one of the following formats:

Add 2, 2   'no parentheses ( ) around the two values

or

CALL Add(2, 2)
@2016-01-03 12:13:54

Calling a Function

To call a function in VBSscript, you can use parentheses around the values you pass to the function. If you use Call syntax to call any function, the function's return value is discarded.

Dim result

result = Add(2, 2)

or

Add 2, 2
@2016-01-03 12:36:58

Exit Function Statement

The Exit Function statement causes an immediate exit from a Function procedure. Program execution continues with the statement that follows the statement that called the Function procedure.

The following example illustrates the use of the Exit Function statement, which causes an immediate exit from a Function procedure.

Function BinarySearch(. . .)
    . . .
    ' Value not found. Return a value of False.
    If lower > upper Then
        BinarySearch = False   
        Exit Function 
    End If
    . . .
End Function

Comments

You must Sign In to comment on this topic.


© 2024 Digcode.com