VBScript: Functions and Loops

In our last tutorial, we discussed statements and multidimensional arrays. In this article we are going to pick up on functions and work our way through to loops. It's a lot to cover in a short amount of time, so buckle up and put on your helmet. No not your special helmet...the other one.

Contributed by
Rating: 4 stars4 stars4 stars4 stars4 stars / 6
December 17, 2007
Rate this Article:
MEH MEH++


SEARCH ASP FREE
TOOLS YOU CAN USE

advertisement

Functions

My old boss used to say to me all the time, "James...I don't know how you live." I won't say why he said that. Just know that he did. Granted the guy is worth like $100 million, so in all honesty, I REALLY don't know how he lives either, though I would sure like to. But I think what he was really saying was: I don't know how you function. So let's talk about functions.

Aside from the built-in functions in VBScript (such as document.write), you can also create your own functions. In VBScript (and every programming language really), functions are used to save programmers from having to write the same bit of code over and over again. Imagine a video game like Mike Tyson's Punch Out. Every time you press the "b" button, Little Mac throws a left-handed punch to the stomach. The pressing of that "b" button calls or triggers the function. That, in turn, tells the program to have Little Mac throw that punch. Now imagine that the programmer had to program the same code over and over every time that punch was thrown. It would result in a billion lines of code and a very angry programmer.

But with functions, he can program it once and then simply call it when the user presses the "b" button.

Our First Function

So let's create a simple function to write some things to the screen:


<html>

<head>

<script type="text/vbscript">

Function myFunction()

document.write("I hold these truths to be self-evident <br />")

End function

</script>

</head>

<body>

<script type="text/vbscript">

myFunction

myFunction

myFunction

myFunction

myFunction

myFunction

myFunction

myFunction

myFunction

myFunction

</script>

</body>

</html>

The above code creates a function that, once called, will print out some text to the browser. We then call the function, not once, but ten times. Each time the function is called, it will print out our text. Here is the result:

  I hold these truths to be self-evident
  I hold these truths to be self-evident
  I hold these truths to be self-evident
  I hold these truths to be self-evident
  I hold these truths to be self-evident
  I hold these truths to be self-evident
  I hold these truths to be self-evident
  I hold these truths to be self-evident
  I hold these truths to be self-evident
  I hold these truths to be self-evident

You may have noticed that we write a function like this: Function myFunction(). The parentheses can be used for holding an argument. In the following example we will create a function to do some math:


<html>

<head>

<script type="text/vbscript">

Function calc(monkey, soup)

calc = monkey + soup

End function

Dim answer

answer = calc(20,30)

document.write(answer)

</script>

</head>

<body>

</body>

</html>

This will create a function that, once called, will add the values in the variables and print the result to the screen:

  50

Note that the values get added to our variables in this line of code: answer = calc(20,30). And that the variables are the arguments in parentheses when we create our function: Function calc(monkey, soup).

You can also use the function in a pop-up box, like so:


<html>

<head>

<script type="text/vbscript">

Function calc(monkey, soup)

calc = monkey + soup

End function

Dim answer

answer = calc(20,30)

msg.box "20 + 30 equals " & answer

</script>

</head>

<body>

</body>

</html>

This will create a pop-up box with the result of the equation: 50.

Sub Procedures

A sub procedure is similar to a function, except that it does not return a result.


<html>

<head>

<script type="text/vbscript">

sub meatballSub()

msgbox("Look at me! I'm a sub procedure!")

end sub

</script>

</head>

<body>

<script type="text/vbscript">

call meatballSub()

</script>

</body>

</html>

This results in a pop-up box that displays the text: Look at me! I'm a sub procedure!

Loop Flakes...They're Great!

Earlier, I said that functions save lazy programmers time. Well, I have more good news for all you slackers: so do loops. Loops allow programmers to repeat blocks of code a certain amount of times, depending on the type of loop and the criteria the programmer has set upon them. There are several types of loops in VBScript.

The For...Next Loop

If you know in advance how many times you would like a particular line of code to execute, you can use the For...Next Loop. The For Loop consists of two statements: the For statement, which creates the counter variable and assigns it a start and end value, and the Next statement, which increases the variable value by one.

Here is some code to count to ten:


<html>

<body>

<script type="text/vbscript">

for i = 1 to 10

document.write( i & " " )

next

</script>

</body>

</html>

Here we create the counter variable "i," and tell it to execute the document.write 10 times (for i= 1 to 10). Each time through the loop, the value in "i" is increased by1 until it reaches the number 10, at which point the loop is exited. Here is the result:

  1 2 3 4 5 6 7 8 9 10

I can also print out text a certain amount of times. If I were at a wrestling match in the 1980s and the Iron Sheik came out, I could create a program to chant USA USA USA over and over again:


<html>

<body>

<script type="text/vbscript">

for i = 0 to 5

document.write("USA!")

next

</script>

</body>

</html>

The result:

  USA! USA! USA! USA! USA! USA!

Stepping it Up

You can use the Step keyword to increase or decrease the value of the counter variable. If we wanted to increase the value by 5, we would use Step 5. If we wanted to decrease the value by 5 we would type Step -5. Here is an example. Prepare to have your minds blown!


<html>

<body>

<script type="text/vbscript">

for i = 2 to 8 Step 2

document.write(i & "<br />")

next

</script>

<p> Who do we appreciate?</p>

<p>Yamatasito Shitso Corp, Yamatasito Shitso Corp, YAY Yamatasito Shitso Corp!</p>

</body>

</html>

The result of our cheer leading code would be:

  2
  4
  6
  8

  Who do we appreciate?

  Yamatasito Shitso Corp, Yamatasito Shitso Corp, YAY Yamatasito Shitso Corp!

And now...a countdown:


<html>

<body>

<script type="text/vbscript">

for i = 10 to 0 Step -1

document.write("T-Minus " & i & "<br />")

next

</script>

<p><h1>Blastoff!</h1></p>

</body>

</html>

The result:

  T-Minus 10
  T-Minus 9
  T-Minus 8
  T-Minus 7
  T-Minus 6
  T-Minus 5
  T-Minus 4
  T-Minus 3
  T-Minus 2
  T-Minus 1
  T-Minus 0

Blastoff!

And here, we will loop through some headers, Wizard of Oz style:


<html>

<body>

<script type="text/vbscript">

for i=1 to 6

document.write("<h" & i & ">I'm Melting!" & "</h" & i & ">")

next

</script>

<p><h2><i>What a cruel world when a little girl can destroy my beautiful wickedness!</i></h2></p>

</body>

</html>

The result:


I'm Melting!

I'm Melting!

I'm Melting!

I'm Melting!

I'm Melting!
I'm Melting!

What a cruel world when a little girl can destroy my beautiful wickedness!

The For Each...Next Loop

The For Each...Next loop will iterate a block of code for every item or element in a collection or array:


<html>

<body>

<script type="text/vbscript">

dim lame(2)

lame(0) = "I"

lame(1) = "Hate"

lame(2) = "Huckabees"

for each x in lame

document.write(x & "<br />")

next

</script>

</body>

</html>

The result of this magnanimous code is:

  I
  Hate
  Huckabees
 

Do Loop

There are several types of Do Loops. They are all used when you want to execute a block of code, but don't know how many times you will want to do so. Basically, the block of code is repeated while a given condition is true or until that condition becomes true.

How to Repeat While a Condition is True

Do While Loop:

<html>

<body>

<script type="text/vbscript">

i=0

do while i < 10

document.write("Beer!" & "<br />")

i=i+1

loop

</script>

</body>

</html>

The above code will continue to loop while the value of "i" is less than 10. Each time through the loop it prints out the delicious word "Beer" and adds one to the counter variable. Note that if the value of "i" had been 9 or greater, the code would never have executed.

If you wanted to ensure that the code executed AT LEAST once, even if the value of "i" was ten, you could also do this:


<html>

<body>

<script type="text/vbscript">

i=10

do

document.write("Beer!" & "<br />")

i=i+1

loop while i < 10

</script>

</body>

</html>

Which would result in:

  Beer!

Do Until

If you wanted to execute some code until a certain condition became true, you could use the Until Keyword, like so:


<html>

<body>

<script type="text/vbscript">

i=1

do Until i=10

document.write("Beer!" & "<br />")

i=i+1

Loop

</script>

</body>

</html>

Again the result:

  Beer!
  Beer!
  Beer!
  Beer!
  Beer!
  Beer!
  Beer!
  Beer!
  Beer!

And we can, of course, force this code to execute AT LEAST once as well:


<html>

<body>

<script type="text/vbscript">

i=10

do

document.write("Beer!" & "<br />")

i=i+1

Loop until i=10

</script>

</body>

</html>

Since the value begins at 10, here is the result:

  Beer!

While that isn't everything there is to know about loops and functions, it is a good start, and I am currently all out of time. My next VBScript tutorial will discuss some of the different types of functions in VBScript, like array and date functions, and go more in-depth on how to use them. So check back often.

Till then...

blog comments powered by Disqus
BRAINDUMP ARTICLES

- Microsoft Windows 8 Committed to Cloud Compu...
- Independent Developers Favor Windows Phone 7
- Dell Introduces VMware-based Cloud
- Microsoft and Skype Agree to Acquisition Deal
- Transfer Contacts in Microsoft Outlook
- Zune`s Next Steps
- Safari Books Online Review
- Does Microsoft Get Touch Screens Now?
- Microsoft`s Record Quarterly Earnings Not En...
- Basic Operations and Registers in Assembly
- Assembly Coding within Visual C/C++ IDE
- New Microsoft Office Coming with a Twist
- Microsoft`s FUSE Labs Unveils Spindex Social...
- HP Slate with Windows 7: Dead or Alive?
- Windows Phone 7 Mobile OS to Rival Android a...

ASP Web Hosting ASP.Net Web Hosting Windows Web Hosting
 
 
 

ASP Free Forums 
 RSS  Tutorials RSS
 RSS  Forums RSS
 RSS  All Feeds
Site Map 
Request Media Kit
Write For Us Get Paid 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Privacy Policy 
Support 


© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 6 - Follow our Sitemap
Most Popular Topics
All ASP.Net Tutorials