AlphaZone Computer Resource Center

           

           VB-SCRIPT COURSE                                            

 

                                   

What is VBScript?

What is VBScript?

VBScript is a scripting language used within web pages to do something cool such as dynamically changing an image, setting a cookie, or controlling DHTML. VBScript is like JavaScript/JScript in that they are both embedded web page scripting languages. VBScript, on the other hand, is based off of the Visual Basic programming language while JavaScript is based off of the Java language. So if you know some Visual Basic then a lot of the VBScript language will seem familiar to you. Keep in mind that VBScript is only supported in Internet Explorer, so only the users with Internet Explorer can execute VBScripts.

Both VBScript and JavaScript/JScript are commonly known as interpreted languages. An interpreted language is one where the code is read, translated and executed all on the fly, line-by-line. Unlike other languages, such as C/C++ or Java, where the code is read and translated, or compiled, into another file all at once and executed separately. One difference between an interpreter and a compiler is that an interpreter will stop when it finds an error whereas a compiler will just list all the errors in the code at once.


Getting Started
All you need is your basic Text editor such as notepad, an internet browser to view your web pages with the VBScript such as Internet Explorer or Netscape, basic HTML Knowledge and patience of steel.

In order to embed the VBScript we have to put the VBScript between the <script> and </script> tags. The script tags are commonly put between the <head> and </head> but can also be put within the <body> and </body> tags. Then we set the language property of the <script> tag to equal "VBScript" like below.

   <head>
   <script language="VBScript">
   <!--
   '...VBScript commands
   -->
   </script>
   </head>

 

This tells the browser what language we're scripting in. Other possible languages include JavaScript, JavaScript1.1, JScript, etc. Notice the <!-- --> surrounding the VBScript. These are HTML comments that are neccessary to hide the script from older browsers that don't understand the <script> tags. Finally, you put all your VBScript between the comment tags. It's as simple as that.  


Variables: Data Types

 

What's a Variable?
A variable is the basic component of a program, or in our case, a script. They are what hold the data we use. Variables are given names that we can easily use, and in turn can be used to represent any value we give to it. We can create, edit or destroy variables. Unlike most programming languages, VBScript only has one data type. A data type is a type of data certain variables are allowed to hold such as numbers or words. All variables in VBScript are of type
'Variant', sort of like a variable variable. A Variant can contain either numerical or string data, it's the context in which it's used that determines how the interpreter treats the variable.

There are, on the other hand, subtypes that can be used to further distinguish a Variant. These are useful when you want a specific data range. Below is a list of the subtypes that a Variant can have.

Subtypes

Description

Boolean

Data that consists of two values, true or false.

Byte

A type that can have an integer in the range 0 to 255.

Integer

A type that can have an integer in the range
-32,768 to 32,767.

Long

A type that can have an integer in the range
-2,147,483,648 to 2,147,483,647.

Single

A type that can have a floating-point, single precision number in the range -3.402823E38 to -1.401298E-45 for negative numbers, and 1.401298E-45 to 3.402823E38 for positive numbers.

Double

A type that can contain a floating-point, double precision number in the range -1.79769313486232E308 to -4.94065645841247E-324 for negative numbers, and 4.94065645841247E-324 to 1.79769313486232E308 for positive numbers.

String

A type that can contain a string of characters up to about 2 billion characters in length.

Currency

A type that can contain a number between
-922,337,203,685,477.5808 and 922,337,203,685,477.5807.

Date (Time)

A type that can contain a number that represents a date between January 1, 100 to December 31, 9999.

Object

A type that can contain an object.

Error

A type that contains an error number.

Empty

An uninitiated variant with the value 0 for numerical variables and "" for string variables.

Null

A type intentionally set with no valid data, nothing, zip, nada!


Variables: All About Variables

 

Declaring a Variable

Before you can use a variable, you must declare it, or let the computer know you're are creating it. There is two ways you can declare a variable, explicitly or implicitly.

When you declare a variable explicitly, you clearly state in your code that you will be using that variable. You do this with the Dim, Public and Private statements. Don't worry about Public or Private right now. Below is an example of how you would use the Dim statement to declare a variable.

   'This declares a variable called "numberOfCows"
Dim numberOfCows

 

If you were wondering, Dim stands for dimension. Above we declared a variable called numberOfCows with which we can store numbers or strings since it's a Variant data type. This is the recommended way to declare variables because you know exactly what variables exist.

Implicitly declaring variables means simply using a variable without the Dim statement. This is not recommended because it leads to rather confusing code. Below is an example of implicitly creating a variable.

   numberOfCows = 3

The computer just assumes this is a variable and sets aside space for it just like it does with the Dim statement.

 

The Naming of a Variable
     When it comes to naming a variable, certain rules must be followed.

  1. The Variable must start with an alphabetic character.
  2. It can't contain a period.
  3. It must be shorter than 255 characters.
  4. There can't be another variable with the same name in the same scope.

 

Assigning Values to Variables

After you declare a variable, the next thing you want to do with it is give it a value. We use the assign operator, or the equal sign ("="), to do this. Below is an example.

   'This assigns 12 to numberOfCows
   'and "Betty Cow" to cowName
   Dim  numberOfCows
   Dim  cowName
   numberOfCows = 12
   cowName = "Betty Cow"

 

We now can use numberOfCows to represent the number 12 and cowName to represent the string "Betty Cow". Notice that we enclose "Betty Cow" in quotes. This tells the computer that the value is to be recognized as a string. Below is an example of using numberOfCows.

   'This assigns the value of numberOfCows (12)

   'to moreCows
   Dim moreCows = numberOfCows

 

Once a variable is assigned a value, the value it originally contained is erased and replaced with the new one. So watch where you plop your values. For example, if moreCows had the value of 3, then the code above would erase 3 and replace it with 12.

 

Who Can See the Variables?

We refer to a variable's visibility as scope. Only the code that the variable was declared in can see it. For example, if a variable wasn't declared in any procedures, then everything can see that variable. It's what is known as a global variable. On the other hand, if a variable is declared within a procedure, only the code within the procedure could see it. That variable exists only when the procedure it's in is being executed. More about procedures later.

 

Constants

A quick word about constants. Constants are just the opposite of variables. Variables can contain changable values whereas constants can contain only one value throughout the program, a constant value. You declare a constant like you did a variable, accept with the Const statement. Below is an example

   'This creates a constant called conCowLegs
   'and gives it a value of 4
   Const conCowLegs = 4

     Above, conCowLegs is given the only value it can ever have. Once you give a constant a value, it's stuck in the variable until the script ends. These are useful for replacing long complicated numbers such as pi (3.141592658) with meaningfully named constants such as conPI.

 


  Variables: Operators

 

Operating on Variables

Now that we know how to create and give variables life, lets operate on them a bit.

Note: no variables were hurt during the writing of this tutorial!

 We use something Operators to manipulate our variables. You'll probably be familiar with most of them because they include the basic mathematical operators such as +, -, * and /. Let's start with a simple operation.

   'This adds a to b giving the answer to c
   Dim a,b,c
   a = 5
   b = 3
   c = a + b 

 

First, notice we can declare multiple variables with one Dim statement by separating them with commas. This adds a and b together and gives the answer to c. If we were to look into the variable c we would see the number 8. Below are some more examples.

   'These do various operations to 

   'a and b giving the answer to c
   Dim a,b,c
   a = 6
   b = 3
   c = a - b  'c = 3
   c = a * b  'c = 18
   c = a / b  'c = 2

 

Operators take two values, perform some type of operation, and pass them to the next operator in line. For example, the addition ("+") operator takes a and b and adds them together, giving the result to the assignment ("=") operator to use. The assignment operator then shoves that value into c.      We could extend the use of operators to evaluate algebraic equations such as surface area of a cube or circle. Below is an example of a script that computes the perimeter of a square and displays the answer using the msgbox function.

   'This computes the perimeter of a square and

   'displays it using the msgbox function
   Dim perimeter, length, width
   length = 4
   width = 8
   perimeter = length * 2 + width * 2
   msgbox perimeter

 

The msgbox function is a built-in function that displays a little window with the data you pass to it, in our case, perimeter. When programming long expressions like the one above, evaluation in programs follow a specific order or precedence. Below is the order things are evaluated.

  1. Anything within parenthesis from left to right. ("()")
  2. Any exponents from left to right. ("^")
  3. Any multiplication or division from left to right. ("*,/")
  4. Any addition or subtraction from left to right. ("+,-")

 

The Mathematical Operators
     Below is a table of the mathematical operators that are available in VBScript.

Symbol

Description

+

Addition: this adds the right and left values together.

-

Subtraction: this subtracts the right value from the left value.

*

Multiplication: this multiplies the right and left values together.

/

Division: this divides the left value by the right value.

\

Integer Division: this divides the left value by the right value and truncates the answer.

^

Exponent: this raises the left value to the power of the right value.

Mod

Modulus: this divides the left value by the right value and returns the remainder left over.

&

String Concatenation: this appends the value on the right to the value on the left, returning a new string.

     A note about the string concatenation operator. This is used to join two strings together. For example.

   'This concatenates two strings!
   Dim sentence
   sentence = "Hello," & " World!"
   msgbox sentence

 This can also be used to append numerical data to a string.


Variables: Arrays

 

What's an Array

An array is a series of values that are all related and can all be accessed through a common variable. Remember that a variable can only contain one value at a time. Once a new value is assigned to it, the original value gets destroyed. Think of a variable as a single box. You can only put one thing in it at a time. Now think of an array as cardboard dividers within the box. This allows you to put multiple things in the box, one thing in each cardboard slot. That's basically what an array is.

Creating an Array

Creating an array is simple. You must use the Dim statement with the array name and size of the array enclosed in parenthesis. Below is an example of what an array declaration looks like.

   'This creates an array called 

   'cowNames that's 11 elements long
   Dim cowNames(10)

 

The pair of parenthesis tell the computer that this variable is going to be an array. The number within the parenthesis specifies how many sections there should be in the variable. There are now 11 separate sections in the cowNames variable that can each hold a variable. The sections are commonly called the elements of an array. You're probably asking "If the array is 11 elements long, why do we have 10 as the number in the parenthesis?" VBScript is zero based, meaning the arrays start at zero. So our elements are numbered: 0,1,2,3,4,5,6,7,8,9,10, which add up to 11 separate elements.

 

Using Arrays

That's good and all but how do we use arrays? Simple, by using the array name with the parenthesis and the number of the element you want to access. Below is an example.

   'This is how you access an array
   cowNames(0) = "Betty Cow"
   cowNames(1) = "Bessie Cow"   
   cowNames(10) = cowNames(1)
     This is just like using a variable but with an added dimension. You just have to specify what element of the array you want to use. Element 0 of cowNames contains the string "Betty Cow" while element 10 of cowNames contains the string "Bessie

The Next Dimension

The arrays we've made so far are only one dimensional arrays. We can make multi-dimensional arrays though. We can go all the way up to 60 dimensions if we wish, but it gets pretty confusing after three. Think of multi-dimensional arrays as putting cardboard separators within cardboard separators. So how would we declare a multi-dimensional array? Like we did above but with added numbers in the parenthesis. Below is an example.

   'This is a two dimensional array
   Dim cowNamesPerFarm(10,4)

This creates an array with 11 elements that are each further divided into 5 elements. This creates what is called a matrix in mathematics. You access a multi-dimensional array the same way you would with a one dimensional one. Below is an example.

   'This gives the cowNamesPerFarm matrix some values.
   cowNamesPerFarm(0,0) = "Betty Cow II"
   cowNamesPerFarm(5,2) = "MooSue"
   cowNamesPerFarm(10,4) = "The Last Cow"

     Everything you can do to a variable, you can do to an array, including mathematical operations and such. You'll see that arrays and matrices come in real handy when used together with loops.

 


Conditionals: If . . . Then . . . Else

 

Making the Computer Think

Conditionals are statements that instruct the computer to do one thing or another based on some kind of expression. There are two types of conditionals in VBScript, If...Then...Else and Select Case.

 

If...Then...Else

If...Then...Else statements performs some type of test and executes certain statements based in the truthfulness of the test. Below is an example.

   'If a = 4 then the msgbox function is called
   Dim a
   a = 4
   If a = 4 Then msgbox "A equals 4"

 

The above if statement does just what it says, if the variable a equals 4 then display a message box with the text "A equals 4". The test is a = 4, and if it is true then the computer goes on to execute whatever statement is after the Then statement. Otherwise, it ignores the Then statement and continues on with the program.  Conditionals use something called conditional operators for the tests. Below is a list of the conditional operators you can test with.

Conditional Operators

Symbol

Description

=

Equal to: evaluates to true if the left value is equal to the right value.

>

Greater-Than: evaluates to true if the left value is greater-than the right value

<

Less-Than: evaluates to true if the left value is less-that the right value

>=

Greater-Than or Equal to: evaluates to true if the left value is greater-than or equal to the right value.

<=

Less-Than or Equal to: evaluates to true if the left value is less-than or equal to the right value.

<>

Not Equal to: evaluates to true if the left value doesn't equal the right value.

Is

Object Equal to: evaluates to true if the left value is the same object as the right value.

 

So you can use these various operators to test for every case possible. Below is some more examples using some of these operators.

   Dim a
   a = 4
   If a > 1 Then msgbox "a is greater-than 1"
   If a <= 5 Then msgbox "a is less-than or equal to 5"
   If a <> 4 Then msgbox "a doesn't equal 4"

 

Notice that in the last If statement that a does equal 4 so it will evaluate to false since the test is looking for a number that doesn't equal 4.

 

The Else Statement
 

Now lets talk about the Else statement. We use the Else statement when we want to do something as a result of the test evaluating to false. Below is an example of how that would look.

   'If a = 1 display a message box with "true!" in it.

   'Otherwise display a message box with "False!" in it.
   Dim a
   a = 4
   If a = 1 Then msgbox "True!" Else msgbox "false!"

 

Here, the statement tests the expression a = 1 and if it is true then executes whatever is after the Then statement. Otherwise, whatever is after the Else statement is executed. So the computer executes one of two things based on the test.

 

The Block Format
 

All the examples so far have been using a single-line format, meaning the whole statement is contained on one line. This is okay when you have only one statement you want to execute as a result of the tests, but what if you want a whole block of statements executed? Then you use the block format of the If...Then...Else statement. Below is an example of how you would do that.

   'If a = 4 display a series of message boxes.
   Dim a
   a = 4
   If a = 4 Then 
      msgbox "This is statement 1!" 
      msgbox "This is statement 2!" 
      msgbox "a equals " & a
   End If

 

All you have to do is enclose the block of statements you want executed between the If...Then statements and an End If statement. The End IF statement marks the end of the statements to perform as the result of the test. You must have the End If statement if you want multiple statements in an If...Then...Else statement. If you forget it, the script will generate an error on your page. You can extend this to work with the Else statement too.

   'If a = 4 display a series of message boxes,

   'otherwise display different message boxes.
   Dim a
   a = 1
   If a = 4 Then 
      msgbox "This is statement 1!" 
      msgbox "a equals " & a
   Else
      msgbox "a doesn't equal 4!" 
      msgbox "a equals " & a      
   End If

 

If the test evaluates to true, then the first block of statements are executed, (between Then and Else), otherwise the second block is executed, (between Else and End If).

 

One More Statement

There is a variation to the If...Then...Else statement that allows you to make multiple tests. It uses the ElseIf statement. You would put this statement where an else statement would normally go. Below is how it would look.

   'If a = 2 display "a equals 2",

   'otherwise if a = 1 display "a equals 1",

   'otherwise display "a doesn't equal 1 or 2.
   Dim a
   a = 1
   If a = 2 Then 
      msgbox "a equals 2!" 
   ElseIf a = 1 Then
      msgbox "a equals 1!" 
   Else
      msgbox "a doesn't equal 1 or 2!"       
   End If

 

You can put as many ElseIf statements within the block as you wish. This is good in case you're testing for multiple values. In the next section, you'll learn about another conditional that is perfect for this type of multiple value test.


 

Conditionals: Select Case

 

Select Case

A Select Case statement is a more efficient alternative to the If...Then...ElseIf...Else statement. Instead of making multiple tests for truthfulness, as in the If...Then...ElseIf...Else structure, Select Case makes only one test, at the beginning of the structure, and compares the results from the test against multiple answers. Then it executes a block of statements that are associated with that particular answer. Below is what a Select Case statement looks like.

   'This makes multiple comparisons

   'of "cows" against the values 10,11, and 12.
   Dim cows
   cows = 12
   Select Case cows
      Case 10
         msgbox "There are 10 cows!"
      Case 11
         msgbox "There are 11 cows!"
      Case 12
         msgbox "There are 12 cows!"
   End Select

 

Notice that the expression is represented at the beginning of the statement, after the Select Case statement. The computer takes whatever is after the Select Case statement, evaluates it, and compares the results against the values after each Case statement. If a match is found between the results and a Case statement, the block of statements after the Case statement are executed, ignoring the rest of the statements in the Select Case statement. Then the computer jumps out of the structure to continue on its way. The whole thing is closed off with a End Select statement. This tells the computer where the end of the Select Case structure ends.

 

Here's another example using strings and with an expression to actually evaluate.

   'This makes multiple comparisons

   'of "cownName" against different strings.
   Dim cowName
   cowName = "Tootie"
   Select Case cowName & " Cow"
 

      Case "Betty Cow"
         msgbox "Moo, Betty!"
 

      Case "Tootie Cow"
         msgbox "Moo, Tootie!"
 

      Case "Bessie Cow"
         msgbox "Moo, Bessie!"
 

   End Select

 

The expression evaluates to "Tootie Cow" since the "&" operator combines the left and right values together. Notice we can also use strings in the comparisons. That's it for the conditionals.

 

Logical Operators

There's one more thing we haven't talked about yet and that's logical operators. Logical operators are used in conditionals to make advanced evaluations. Their operands, or the values they work on, are expressions themselves such as a = 1. Below is a table with most of the logical operators available in VBScript.

Logical Operators

Symbol

Description

Not

Logical Negation: Changes a value of true to false and vice-versa.

And

Logical Conjunction: evaluates to true if the left value and right value are true.

Or

Logical Disjunction: evaluates to true if the left value or right value are true.

Xor

Logical Exclusion: evaluates to true if one of the left or right values are true, but not both.

Eqv

Logical Equivalence: evaluates to true if the left and right value have the same truthfulness.

Here are some examples using logical operators.

   Dim a
   a = 7
   If a = 7 And a < 10 Then 'This is true
   If a < 8 Or a <> 7 Then 'This is true
   If a > 6 Xor a = 7 Then 'This is false
   If a = 9 Eqv a < 3 Then 'This is true
   If Not a = 7 Then 'This is false

 


Looping

 

What are Loops?

Loops provide a way to execute a block of code repeatedly, which saves us a lot of programming. They loop until some type of condition is met such as a variable equaling some number. There four types of loops in VBScript, but we are only going to concern ourselves with two. The two we are going to talk about are the Do...Loop and For...Next loops.

 

The Do...Loop Loops

The Do...Loop repeats a block of code while, or until, a condition is met. We use the While and Until statements to specify how the condition is treated. Below is the general structure of a Do...Loop.

   Do While|Until condition
      'The block of statements to repeat

      '...
   Loop

 

The loop starts out with the Do statement and either the Until or While statement following it. Then after that is the condition that will be evaluated with every loop and, depending on what statement you used, While or Until, will decide whether to continue or end the loop. The While statement will continue to loop while the condition is true whereas the Until statement will continue to loop until the condition is true. The Loop statement marks the end of the block of code to repeat so all of the code you want repeated goes in between the Do and Loop statements. Below is an actual script that uses a loop.

   'This loops while "counter" is

   less than 3, displaying "counter" each time
   Dim counter
   counter = 0
 

   Do While counter < 3
      counter = counter + 1
      msgbox "counter is at " & counter
   Loop      

 

 What it does is, upon entering the loop, tests to see if counter is less than three. If it is less than three, the program flow continues on within the loop. It increments counter and displays the new value of counter. Then when the computer reaches the Loop statement, it goes back up the to beginning of the loop to reevaluate the condition. Finally, after three repetitions, when counter equals three, the loop stops because the test counter < 3 evaluates to false.

Note: You can make the loop execute at least once by putting the Until or While statement with the condition after the Loop statement. This makes the computer evaluate the condition at the end of each loop instead of the beginning.

 

The For...Next Loops

The For...Next loop is a little more complicated. This loop will repeat a block of code a set number of times. It uses a variable to hold the current number of times the loop has executed and at the beginning of each loop, tests this variable against the number to stop at. Below is what the general structure looks like.

   For aVariable = startingNumber to endingNumber
      'Block of statements to execute

      '...
   Next

 

You start off the loop with the For statement and then the name of the variable you want to hold the current loop number. Above we called it aVariable. You assign the variable the number you want the loop to start counting at. Then we put the To statement followed by the number we want aVariable to equal before stopping. The For...Loop automatically increments aVariable by 1 so you don't have to worry about it. Below is an example of a For...Next loop.

   'This loops 4 times, each time 

   'displaying the value of "cnt"
   For cnt = 0 To 3
      msgbox "Loop number: " & cnt
   Next

 

Notice that we can use the variable that is holding the number of times the loop has gone through. The loop executes four times because we started cnt at 0.

That's not all you can do with For...Next loops. You can also increase the counter variable by bigger increments or even count down by using the Step statement. Simply put the Step statement at the end of the For statement's line with the number to increment, or decrement, by. Below is an example.

   'This loops 4 times, each time displaying 

   'the value of "cnt" which is incremented by 5
   For cnt = 0 To 15 Step 5
      msgbox "Loop number: " & cnt
   Next

 

The cnt variable is increment by 5 with every loop. You can also put a negative number such as -1 as the Step value and have it count down instead of up. But make sure that you start the variable off at a higher number than where to stop at because your loop could loop forever and freeze your browser for a bit.

 

Using Loops With Arrays

Arrays and loops go together like, milk and cereal, fish and water, cows and software..., well sort of. With For...Next loops you can access all the elements in an array by replacing the number in the array's parenthesis, (or the array index), with the loop-counting-variable. Below is an example.

   'This loops 6 times, each time displaying 

   'assigning a number value to each element in 

   '"cowIDNumber" and displaying it.
 

   Dim cowIDNumber(5)
 

   For cnt = 0 To 5
      cowIDNumber(cnt) = 100 + cnt
      msgbox "Cow #" & cnt & " ID: " & cowIDNumber(cnt)
   Next

 

What it does is assigns a value to each element in the cowIDNumber array and displays it within a string. The value assigned is the current loop number plus 100. Notice how the string is just a bunch of pieces joined together with the concatenation operator, ("&"). You could even go further by nesting another For...Next loop within this one and scale through a two dimensional array.

 


Procedures: Subs

 

What Are Procedures?

Procedures are little blocks of code that can be summoned up and executed by simply referencing the name of the procedure. They make code more efficient and smaller by putting commonly executed statements into one common place. That way to don't have to type out the whole chunk of code for every place you want to use it. You just put the code in a procedure block, name it, and call it whenever you want the code inside to execute. There are two types of procedures, subs and functions.

How Do you Make a Sub?

A sub is made with the Sub and End Sub statements. Keep in mind that all procedures must be declared to have a script-level scope. Script-level scope is when something is declare between the <script> tags and not within another procedure. It's another name for global scope. Below is the general structure of a sub.

   Sub subName(arguments,...)
      'The procedure's statements

      '...
   End Sub

 

Now for an explanation. The sub starts out with the Sub statement along with the name of the sub. This is the name you will use to reference the sub. After that is a pair of parenthesis with a list of the variables that will hold the arguments that were passed to the sub.

 

You may be asking "What's an argument?" Well, procedures are like little islands of code that are completely cut off from outside world, or in our case, the code outside the procedure. So if we want it to use some data that is on the outside world, we have to pass it to the procedure in the form of an argument, unless the data has a global scope in which everything can see it automatically. When calling procedures, arguments are the values placed after the procedure name. Msgbox is an example of a procedure, a built-in one that is. What ever you put after the statement msgbox, is passed to the msgbox procedure, which then does the work to display the argument you gave to it.

Remember when we talked about scope in part 2.2 on variables ? Well, everything within a procedure can only see itself. It's scope is limited to itself. This is a good thing though, because it makes code cleaner and less prone to corruption. That's why we must pass data, outside of a procedure, through as arguments. The variables that are in the parenthesis in the Sub statement, are where the argument's values are placed. These are the variables you use within the procedure to represent the arguments that were passed to it. Below is an example of a sub that uses arguments.

   'This uses a sub to display data
   Sub display (data)
      msgbox "Displaying: " & data
   End Sub
 

   display "Hello"
   display 5

 

The display sub is declared and defined. Then called first, with the argument "Hello" and second, with the argument 5. With each call to display, the argument that is passed, of which the value is passed to data, is displayed using the msgbox sub.

If you want to create a procedure that doesn't take any arguments, simply leave the parenthesis after the Sub statement blank. If you wanted to create a procedure that handles multiple arguments, just put a variable in the parenthesis for each argument, separated by commas. Below is an example of a multi-argument sub.

   'This creates a sub that adds

   'two numbers and displays the result.
   Sub addAndDisplay(num1,num2)
      Dim total
      total = num1 + num2
      msgbox num1 & " added to " & num2 & " is " & total
   End Sub
 

   addAndDisplay 10, 45

 

Above, the first argument of addAndDisplay is placed in the first variable (num1) and the second is placed in the second variable (num2). Then they are added and displayed. Notice the variable total that was Dim'ed. That variable's scope is limited to the procedure. Once the procedure ends, any existence of total is erased.

 

 In the next section, we'll learn about the second type of procedures, functions.


Procedures: Functions

 

What's a Function?

A function is the same thing as a sub except that it uses the Function...End Function statements and it returns a value every time it's called. It can be thought of as a machine that takes input, or arguments, processes it, then outputs the processed product. Below is the general structure of a function.

   
   Function functionName(arguments,...)
      'statements to process the input

      '...
      functionName = valueToReturn
   End Function
 

We start out a function the same way as a sub but with the statements Function and End Function in its place. Aside from that the only difference is the line:

   functionName = valueToReturn

 

This line tells the computer to return the value of valueToReturn from the function. That value can be anything you want. So how would you use this value that is returned from the function? As a rule, when ever you call a function, it must be in an expression or on the right side of an equal sign so the value being returned can be assigned somewhere. Below is an example.

   someVariable = someFunction(data1,data2)

 

All functions must be used like this, or there would be no reason to use them. Also, unlike subs, when calling a function, the arguments must be in parenthesis. If it takes no arguments, leave the parenthesis empty "()". Functions are good for putting complex formulas or long algorithms in because it simplifies the code. Below is an example of a function that returns the surface area of an object.

 

   Function surfaceArea(width,height)
      surfaceArea = width * height
   End Function
 

   Dim area
   area = surfaceArea(3,6)
   msgbox area
   msgbox surfaceArea(10,23)
   

 

We declared a function called surfaceArea that takes two arguments, width and height and returns the product of the two. Then we assigned the value returned by surfaceArea(3,6) to area and displayed it. Next we assigned the value returned by surfaceArea(10,23) directly to the msgbox sub to display.

 

After you have a little experience with procedures, it will all begin to fall into place so don't worry if you're a little confused. Remember practice makes perfect, and that can't be more right when it comes to web page scripting.  


Clean Code

 

In this section, we just detail on good coding practices. It's always a good idea to code clean because of the shortened time you spend debugging your scripts. What do we mean by "clean code"? Making code that is easily readable and understandable to not only you but others who may need to edit your script.

When naming your variables and procedures, use short descriptive words all running together. capitalize each word accept for the first one. Use a verb as the first word in a procedure name such as display, do, calculate, etc. Below are some examples.

   someVariable
   currentTime
   curBoxIndex
   displayStatus
   calcTotalCost()

Prefixes
     Below is a list of recommended prefixes that should be added to your variables.

Prefixes

Variable Type

Prefix

Examples

Boolean

bln

blnAnswer

Byte

byt

bytHexColor

Integer

int

intPeople

Long

lng

lngStars

Single

sng

sngAtomMass

Double

dbl

dblQuarkMass

String

str

strName

Currency

cur

curCashPaid

Date (Time)

dtm

dtmReminder

Object

obj

objDisplay

Error

err

errCurrent

 

Comment your code, please, COMMENT YOUR CODE! Just watch, you'll write something thinking, "I'm not gonna forget this block of code!", then after a couple weeks, you go back to it and have to reverse engineer your own creation because the lack of something as simple as comments. So take it from us programmers, it pays to comment. As a rule it's good to describe what all your procedures do. Don't go into how they do it, although, because that may change over time.

 

 

VBScript Operator Reference

Mathematical Operators

Symbol

Description

+

Addition: this adds the right and left values together.

-

Subtraction: this subtracts the right value from the left value.

*

Multiplication: this multiplies the right and left values together.

/

Division: this divides the left value by the right value.

\

Integer Division: this divides the left value by the right valuea and truncates the answer.

^

Exponite: this raises the left value to the power of the right value.

Mod

Modulus: this divides the left value by the right value and returns the remainder left over.

&

String Concatenation: this appends the value on the right to the value on the left, returning a new string.

 

Conditional Operators

Symbol

Description

=

Equal to: evaluates to true if the left value is equal to the right value.

>

Greater-Than: evaluates to true if the left value is greater-than the right value

<

Less-Than: evaluates to true if the left value is less-that the right value

>=

Greater-Than or Equal to: evaluates to true if the left value is greater-than or equal to the right value.

<=

Less-Than or Equal to: evaluates to true if the left value is less-than or equal to the right value.

<>

Not Equal to: evaluates to true if the left value doesn't equal the right value.

Is

Object Equal to: evaluates to true if the left value is the same object as the right value.

 

Logical Operators

Symbol

Description

Not

Logical Negation: Changes a value of true to false and vice-versa.

And

Logical Conjunction: evaluates to true if the left value and right value are true.

Or

Logical Disjunction: evaluates to true if the left value or right value are true.

Xor

Logical Exclusion: evaluates to true if one of the left or right values are true, but not both.

Eqv

Logical Equivalence: evaluates to true if the left and right value have the same truthfulness.

 

1