The VBScript Network and Systems Administrator's Cafe

Mar 10 2008   3:33PM GMT

Working with Subroutines and Functions in VBScript

Jerry Lees Jerry Lees Profile: Jerry Lees

Tags:
Installation
Windows on Intel
Wireless

In this installment, we’ll discuss the advantages of using Subroutines and Functions in your script rather than using a all-in-one script that runs from start to finish. I’ll only give a breif over veiw of subroutines and function, but more information on them can be found in the VBScript User’s guide and Language reference.

First, 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
      Using the same set of code multiple times in the same script without a loop of some type.
      Helpful in debugging a script and disabling a section of code
      Helpful in organising the logic of the script into smaller bite sized pieces

They essentially are the work horse of your script. In General, I try to keep all the logic of a script in a Function or a subroutine– that way If I have to make modifications I’m only going to at worst break a small (but possibly important) piece of the script. Remember, Subroutines and functions can call other subroutines and functions– so they are not limited to just being used within your main script– Infact, a single function or subroutine can call itself! This is outside the scope of this posting, but is called a recursive funtion or subroutine.

They both get passed information when they are called and  preform their work according to what the information they have been given. These values passed can literally be anything you need to make the subroutine or function work. These values are generally only what the function needs to preform it’s work. For example:

Say you need to calculate the price you pay for an item at the store, so you can have exact change in cash. Think about what information you need. You just need the price of the item and any sales tax on the item, you don’t need anything else like where the store is or who the cashier is. That’s essentially what a subroutine is!

Now, Functions and subroutines are VERY similar. In fact, there is only one major difference in the two of them. 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.

The only difference is that 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.  So it’s kind of a loner… just does it’s work and doesn’t bother anyone else with the details or the result. This is useful for file or screen I/O where you don’t need any information returned to you. Basically, it’s a script all in itself. In our earlier example the subroutine would need to print out or do something with the values calculated and no other area of the program would be aware of where the result.

A function on the other hand will communicate back to the calling routine some value… possibly the result of some calculation, like our total price of the item, or an error condition for the calling routine to process and deal with in a manner that is fitting for the situation.

In my example below I provide you with both examples of a subroutine and a function to add two numbers together. Notice that when I call the subroutine in vbscript I do not use parenthesis around the values I pass to the routine, but with a function I do use them. This is just simply the way it is done in VBScript and will result in an error if your do it the other way around.

Option Explicit
Dim ReturnValue

TestSub 2,2 ‘ subroutine call– notice no ( ) around the two values!?!?!
ReturnValue = TestFunction (2,2) ‘function call– notice the ( ) around the two values… plus some thing else!
WScript.Echo “Function returned: ” & ReturnValue

‘ end of main code

Function TestFunction (Value1, Value2)
‘ Function to add two numbers and RETURN the value to the calling routine.

Dim Sum
 Sum = value1 + Value2
 WScript.Echo (“Functions: All your work is done here and used here, but can be sent back to the main script.”)
 WScript.Echo Value1 & ” + ” & Value2 & ” = ” & Sum

TestFunction = Sum

End Function
Sub TestSub (Value1, Value2)
‘ Subroutine to add two values together… notice all the work is done and used here?

Dim Sum
 Sum = value1 + Value2
 WScript.Echo (“Subroutines: All your work is done here and used here.”)
 WScript.Echo Value1 & ” + ” & Value2 & ” = ” & Sum

end Sub

Play with this code… see if you can figure it out. In a few days I will explain it in a bit of better detail. Take note of how I build the function, subroutine, and see if you can figure out the line that does the magic of returning the value from the function. 

Extra Credit: Did you notice the line that had option explicit and the lines that have Dim in them? What do they do? Post a comment and I’ll let you know in a few days.
 

2  Comments on this Post

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
  • Jerry Lees
    Kizo has added a good tip here. Though I don’t know the “state” of the exe this site produces. (If it is JUST that code you type in or if there is extra added in.) I doubt it changes, or adds to, the code but certainly it’s a possibility. basically use any vbs2exe conversion with caution. On a side note, PrimalScript allows you to do the same thing, from a trusted source, and is really simple. Not to mention it comes with the Windows Scripting host installation… I can’t remember how to do it off the top of my head, but I’ll research it more and add it to a later blog entry.
    5,335 pointsBadges:
    report
  • Jerry Lees
    On a side note. My copy of Trend Antivirus 8 found no viruses, but the site would not compile a working executable of the following vbs: wscript.echo "test"
    5,335 pointsBadges:
    report

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to: