Saturday, February 15, 2020

VBScript tutorial 2 | Sub Procedures and Function Procedures

This is the second tutorial in the VBScript Tutorials for Beginners. This VBScript beginner tutorial explains what is procedure in VBScript. Please view the VBScript tutorial 2 or read on... What is procedure? A VBScript procedure is VBScript code that may be re-used wherever we want. The benefit of using procedures in VBScript is that we don't have to code and test the same thing again. Procedures also make our code modular (and more readable). VBScript procedures include Sub procedures and Function procedures.

What is Sub procedure in VBScript? It is VBScript code that starts with the Sub statement and ends with the End Sub statement. A sub procedure may optionally have parameters, which is additional information given during procedure call. Now, let see VBScript sub procedure examples. I have explained Option Explicit statement and InputBox function in my previous VBScript tutorial 1.

' VBScript code - main script starts
Option Explicit
Dim inputWeight
' CDbl function converts a string to a double precision number
inputWeight = CDbl(InputBox("Enter a weight in kilos:"))
' Procedure call to ConvertWeight sub procedure with inputWeight argument
Call ConvertWeight(inputWeight)
'Procedure call to EndScript sub procedure
Call EndScript
' main script ends

' Sub procedure starts
' Kilos is called the parameter in the sub procedure.
Sub ConvertWeight(Kilos)
    Dim Pounds
    Pounds = 2.205 * Kilos
    MsgBox "The weight of " & Kilos & " kg is equivalent to " & Pounds & " lbs."
End Sub
'Sub procedure ends

' Note that the EndScript procedure has no paramater.
Sub EndScript
    MsgBox "Thank you!"
End Sub

Next, let us learn what is Function procedure in VBScript? It is VBScript code that starts with the Function statement and ends with the End Function statement. A function procedure may optionally have parameters. The difference between sub procedure and function procedure is that a VBScript function procedure can provide a return value. This means that we can call a function procedure within a VBScript statement, just as we would call built-in VBScript functions. Now, let see VBScript function procedure examples.
' VBScript code
Option Explicit
Dim inputWeight
inputWeight = CDbl(InputBox("Enter a weight in kilos:"))
' Function call to Pounds function procedure with inputWeight argument
MsgBox "The weight of " & inputWeight & " kg is equivalent to " & Pounds(inputWeight) & " lbs."
' Function call to ExitMessage function, with no argument
MsgBox ExitMessage()

' Function procedure starts
Function Pounds(Kilos)
    Pounds = 2.205 * Kilos
End Function
' Function procedure ends

Function ExitMessage()
    ExitMessage = "Thank you!"
End Function

Want to learn how sub procedures and function procedures work in VBScript? Please view my VBScript tutorial 2. Thank you.

No comments:

Post a Comment