VBScript
Tutorial
VBScript stands for Visual Basic Script, a scripting language
developed by Microsoft to be used with Microsoft products,
mainly Internet Explorer. It has gone through many changes
over the years and is now mainly used as the default
scripting language of ASP.
VBScript:
Client Side Scripting
VBScript was created to allow web page developers the ability to c
reate dynamic web pages for their viewers who used Internet
Explorer. With HTML, not a lot can be done to make a web page
interactive, but VBScript unlocked many tools like: the ability
to
print the current date and time, access to the web servers file system,
and allow advanced web programmers to develop web applications.
VBScript:
Why Learn and Use It?
VBScript is a prerequisite for ASP developers and should be
learned
thoroughly before attempting any sophisticated ASP programming.
Programmers who have used Visual Basic in the past will feel more
at home when designing their dynamic web pages with VBScript,
but it should be known that only visitor's using Internet Explorer
will be able to access your code, while other browsers will not
be able to process the VBScript code.
MYSITE's VBScript Learning: Do's & Don'ts
DO Learn VBScript
- If you have a solid understanding of HTML
- If you want to program successfully in ASP
- If you already know Visual Basic and would
like to experiment with VBScript
- If you are a hobbyist that enjoys knowing many
programming
DON'T Learn VBScript
- If you are developing a web page for the
general public
- If your site has visitors who use a browser
other that Internet Explorer
- If prefer to avoid dying languages. If you
want
- something more supported, you should learn Javascript
If you still want to learn VBScript then let's get started.
VBScript Installation
VBScript is
a client side scripting language that can be developed
in any
text editor. An example of a text editor would be Notepad.
VBScript
is a Microsoft proprietary language that does not
work
outside of Microsoft programs.
VBScript Supported Browsers
After you
have written your VBScript code you need to download the
Internet
Explorer to process your code. Firefox, Opera, Netscape,
VBScript Execute Your Scripts
After you
have installed Internet Explorer to your computer,
you
can run your VBScript by loading your web page that
includes
your VBScript into Internet Explorer. The
VBScript Debugging
If you would
like to enable client side scripting debugging then open up internet explorer
and open the Internet Options. Tools < Internet Options. In the options
popup window choose the Advanced tab from the tab bar.
Contained
here are tens of different options you can manipulate in Internet Explorer. We
simply want to turn on debugging for our scripts, so find the Browser
section. If you are using Internet Explorer for Windows XP then the option Disable
Script Debugging (Internet Explorer) should be the fourth item down in the Browser
section.
Uncheck the option Disable Script Debugging (Internet Explorer) and you
have now enabled scrip debugging. When you are executing your scripts and they
are not functioning properly you can now use the debugger with the menu by
going to View < View Debugger < Open. Note: You will need to restart
Internet Explorer before this option will show up.
VBScript First Script
We like to
teach by example, here at MYSITE.com, so let's start off with a simple VBScript
example that will help you get your feet wet. Reminder: We will not be
explaining the HTML in this tutorial so review our HTML Tutorial if
you ever need extra assistance understanding an example or lesson.
VBScript
Script Creation
This first
script will be very basic and will write "Hello World" to the browser
window, just as if you had typed it in HTML. This may not seem very important,
but it will give you a chance to see the VBScript Syntax without getting to
complex.
VBScript Code:
<html>
<body>
<script
type="text/vbscript">
document.write("Hello
World")
</script>
</body>
</html>
Display:
Note: If you are not using Internet Explorer to view this tutorial then you
will see nothing displayed. This is because VBScript only runs on Internet
Explorer browsers! Just in case you don't have access to Internet Explorer we
will be providing a converted output in the rest of our displays for this
tutorial.
Display:
Hello World
VBScript <script> Tag
In the above
example you saw the basic cookie cutter for inserting a script into a web page.
The HTML script tag lets the browser know we are going to use a script
and the attribute type specifies which scripting language we are using.
VBScript's type is "text/vbscript".
All the
VBScript code that you write must be contained within script tags,
otherwise they will not function properly.
VBScript Syntax
If you are
an expert Visual Basic programmer then you will be pleasantly surprised to know
that VBScript has nearly identical syntax to Visual Basic. However, if you are
a programmer or only know the basics of HTML then VBScript code may look a
little strange to you. This lesson will point out the most important things
about VBScript syntax so you can avoid common potholes.
VBScript: No Semicolons!
If you have
programmed before, you will be quite accustomed to placing a semicolon at the
end of every statement. In VB this is unnecessary because a newline symbolizes
the end of the statement. This example will print out 3 separate phrases to the
browser. Note: There are 0 semicolons!
VBScript Code:
<script
type="text/vbscript">
document.write("No
semicolons")
document.write(" were injured
in the making")
document.write(" of this
tutorial!")
</script>
Display:
No
semicolons were injured in the making of this tutorial!
VBScript Accessing Methods
To access
methods and properties contained within an object, like the Document object,
you use a period "." after the object and before the name of the
method.
So far in
this tutorial we have been using the write method that is a part of the
document object and the syntax for doing this is:
- document.write(string_here)
VBScript Multiple Line Syntax
As we stated
above, the syntax is that placing a newline in your VBScript signifies the end
of a statement, much like a semicolon would. However, what happens if your code
is so long that absolutely must place your code on multiple lines?
Well,
Microsoft has included a special character for these multiple lines of code:
the underscore "_". The following example contains an exceptionally
long write statement that we will break up string concatenation and the
multiple line special character.
VBScript Code:
<script
type="text/vbscript">
document.write("This is a very
long write " &_
"statement that will need to be
placed onto three " &_
"lines to be readable!")
</script>
Display:
This is a
very long write statement that will need to be placed onto three lines to be
readable!
VBScript Syntax Review
VBScript is
a client-side scripting language that is based off of Microsoft's Visual Basic
programming language. No semicolons are used at the end of statements, only
newlines are used to end a statement.
If you want
to access methods of an object then use a period "." and an
underscore is used for statements that go multiple lines!
VBScript Variables
Variables in
VBScript behave just like those variables you would use in Visual Basic. If you
don't know Visual Basic don't worry because we are going to put you through
MYSITE's Five Minute VBScript Variable Bootcamp.
For those of
you who have not used variables before, then you should know that the notion of
variables helps to make programs easier to program and to understand. Variables
are used to hold information so that it can be reused throughout the program.
You can think of variables as a grocery bag and your information you want to
store as your groceries. Without the bag it's going to be a pain the bum to
drag all that food around!
Declaring Variables in
VBScript
When you are
going to use a variable in your VBScript code you should first declare it. To
declare a variable in VBScript you use the Visual Basic Dim statement:
VBScript Code:
<script
type="text/vbscript">
Dim myVariable1
Dim myVariable2
</script>
Display:
Nothing is
displayed because we were simply setting up our variables for use!
Note: It is also possible to declare multiple variables in one line. Use the
comma "," to separate your multiple variable names.
VBScript Code:
<script
type="text/vbscript">
Dim myVariable1,
myVariable2
</script>
Display:
VBScript Variables: Setting
Values
When you
want to set your variable equal to a value you use the equals character
"=", also known as the equals operator. The name of your variable
appears on the left of the equals, while the value you are setting your
variable equal to appears to the right of the equals.
To use your
variable, simply type the variable name where you would like to use it. In this
example we create two variables, set set one equal to a number and the other
equal to a string. We then use the document.write method to print both
out to the browser.
VBScript Code:
<script
type="text/vbscript">
Dim myVariable1, myVariable2
myVariable1 = 22
myVariable2 = "Howdy"
document.write("My number is
" & myVariable1)
document.write("<br />My
string is " & myVariable2)
</script>
Display:
My number is
22 My string is Howdy
VBScript Variables: Setting
Objects
Setting
Objects? Yes, VBScript allows you to use objects in your code. Objects are
blobs of code goo that can contain multiple methods and variable. When you want
to use these methods and variables you have to use the period operator
"." to gain access to them. See our VBScript Syntax lesson for more
information.
When you are
setting a value to a variable that is actually an object then you must
follow some special syntax. The SET keyword lets VBScript know that you
are setting your variable equal to an object. In addition to this, you also
have to set the variable equal to nothing after you are finished with
it! It's a lot of extra work, but it is necessary.
This example
shows how to use a fictional class myClass to create an object. For this
example to work you would have to create myClass yourself. Going into
more detail is behind the scope of this lesson.
VBScript Code:
<script
type="text/vbscript">
Dim myFirstObject
SET myFirstObject = New myClass
myFirstObject = nothing
</script>
Display:
Note: Once again, nothing is displayed because we were just showing you how
to set and release an object in VBScript!
VBScript Operators
Operators
are used to "do operations" or manipulate variables and values. For
example, addition is an example of a mathematical operator and concatenation is
an example of a string operator. The plus sign "+" is the operator
used in programming language to represent this mathematical addition operation
VBScript's
many operators can be separated into four semi-distinct categories:
- Math
Operators
- Comparison
Operators
- Logic
Operators
- String
Concatenation Operator
VBScript Operators: Math
When you
want to perform addition, subtraction, multiplication, and other mathematical
operations on numbers and variables use the operators listed below.
Operator
|
English
|
Example
|
Result
|
+
|
Add
|
8+7
|
15
|
-
|
Subtract
|
11-10
|
1
|
*
|
Multiply
|
7*8
|
56
|
/
|
Divide
|
8/2
|
4
|
^
|
Exponent
|
2^4
|
16
|
Mod
|
Modulus
|
15 Mod 10
|
5
|
VBScript Operators: Comparison
When you
want to compare two numbers to see which is bigger, if they're equal, or some
other type of relationship use the comparison operators listed below. Common
uses of comparison operators are within conditional statements like an If
Statement or the condition check in a While Loop.
Operator
|
English
|
Example
|
Result
|
=
|
Equal To
|
10 =1 4
|
False
|
>
|
Greater Than
|
10 > 14
|
False
|
<
|
Less Than
|
10 < 14
|
True
|
>=
|
Greater Than Or Equal To
|
10 >= 14
|
False
|
<=
|
Less Than Or Equal To
|
10 <= 14
|
True
|
<>
|
Not Equal To
|
10 <> 14
|
5
|
VBScript Operators: Logic
Logic
operators are used to manipulate and create logical statements. For example if
you wanted a variable shoeSize to be equal to 10 or 11 then you would do
something like:
VBScript Code:
<script
type="text/vbscript">
Dim shoeSize
shoeSize = 10
If shoeSize = 10 Or shoeSize = 12 Then
'Some code
EndIf
</script>
A detailed
explanation of Logic and Logic Operators are beyond the scope of this tutorial,
but we do have a list of the various logic operators available to you in
VBScript.
Operator
|
English
|
Example
|
Result
|
Not
|
Inverts Truth Value
|
Not False
|
True
|
Or
|
Either Can Be True
|
True Or False
|
True
|
And
|
Both Must Be True
|
True And False
|
False
|
VBScript String Concatenation
Operator
When you
have various strings that you would like to combine into one string use the
concatenation operator. The concatenation operator acts as a glue between the
two or more strings you wish to attach, effectively making them into one
string. String concatenation is often used when using the document.write
function.
Operator
|
English
|
Example
|
Result
|
&
|
Connected To
|
"Hello" & " there"
|
"Hello there"
|
Be sure to
bookmark this page so that you can use it as a reference if you forget the
various operators available in VBScript.
VBScript Strings
Strings are
a bunch of alpha-numeric characters grouped together into a "string"
of characters. This sentence I am writing right now is an example of a text
string and it could be saved to a VBScript string variable if I wanted it to.
VBScript String Syntax
To create a
string in VBScript you must surround the letters or numbers you wish to be stringanized
(that's a made up MYSITE word) with quotations, like this:
VBScript String: Saving into
Variables
Just like
numeric values, strings in VBScript are saved to variables using the equal operator.
This example shows how to save the string "Hello there!" into the
variable myString and then use that variable with the document.write
function.
VBScript Code:
<script
type="text/vbscript">
Dim myString
myString = "Hello there!"
document.write(myString)
</script>
Display:
Hello there!
VBScript String Concatenation
Often it is
advantageous to combine two or more strings into one. This operation of adding
a string to another string is referred to as concatenation. The VBScript script
concatenation operator is an ampersand "&" and occurs in between
the two strings to be joined. This example will join a total of 4 strings to
form a super string. Note: We only use one variable in this example!
VBScript Code:
<script
type="text/vbscript">
Dim myString
myString = "Hello there!"
myString = myString & " My
name"
myString = myString & " is
Frederick"
myString = myString & "
Nelson."
document.write(myString)
</script>
Display:
Hello there!
My name is Frederick Nelson.
VBScript Arrays
Imagine that
you would like to store a list of all the gifts you would like to receive on
your wedding day. You want to make a web page that displays a list of all the
items. If you were to create a variable for each gift then you might end up
having 100 or more variables for gifts alone! However, there is a better
solution to this engineering problem.
Instead, you
could utilize arrays, which allow you to store many variables(elements) into a
super variable (array). Each present would have a position in the array,
starting from position 0 and ending with the last gift.
VBScript Creating an Array
We are going
to dumb down the example a little bit so that this lesson doesn't get too
boring. Let's imagine that we have 4 gifts we want to store in our array. First
we need to create an array to store our presents and tell VBScript how big we
want our array to be.
As we
mentioned, an array's beginning position is 0, so if we specify an array of
size 3 that means we can store 4 presents (positions 0, 1, 2 and 3)! This is
often confusing for first time VBScript programmers. Below is the correct code
to create a VBScript array of size 3.
VBScript Code:
<script
type="text/vbscript">
Dim myArray(3)
</script>
VBScript Arrays: Storing Data
Now that we
have created our array we can begin storing information into it. The way to do
this is similar to setting the value of a variable, but because an array can
hold many values you have to specify the position at which you want the value
to be saved.
We have four
presents that we need to store and we make sure that we don't store two
presents in the same position!
VBScript Code:
<script
type="text/vbscript">
Dim myArray(3)
myArray(0) = "Clean
Underwear"
myArray(1) = "Vacuum
Cleaner"
myArray(2) = "New
Computer"
myArray(3) = "Talking
Bass"
</script>
VBScript Arrays: Accessing
Data
We have all
the data stored into the array that we need, now we need to figure out how to
get it back out so we can print it to the web page! This step is nearly
identical to the storing phase because you have to specify the position of the
element you wish to display. For example, if we wanted to print out the value
of the present at position 0 in our array you would use the following code:
VBScript Code:
<script
type="text/vbscript">
Dim myArray(3)
myArray(0) = "Clean
Underwear"
myArray(1) = "Vacuum
Cleaner"
myArray(2) = "New
Computer"
myArray(3) = "Talking
Bass"
document.write(myArray(0))
</script>
Display:
Clean
Underwear
VBScript Arrays: Accessing All
Data
The above
example was a good introduction to accessing elements in an array, but it isn't
that helpful for printout out all items that might be in an array. If we
had 300 items in our array, accessing them one by one would be most time
consuming to program.
Below is a
piece of code that will automatically go through every element in the array and
print it out. The special programming structure this example uses is a For Loop
that we will be discussing in greater detail later on in this tutorial.
VBScript Code:
<script
type="text/vbscript">
Dim myArray(3)
myArray(0) = "Clean
Underwear"
myArray(1) = "Vacuum
Cleaner"
myArray(2) = "New
Computer"
myArray(3) = "Talking
Bass"
For Each present In
myArray
document.write(present)
document.write("<br
/>")
Next
</script>
Display:
Clean
Underwear Vacuum Cleaner
New Computer
Talking Bass
VBScript If Statement
One of the
most common programming tools that is required to write any kind of program is
the If Statement. This lesson will give you the basic rundown of how to
implement an If Statement in VBScript.
Making
decisions is a tiring process, so it's nice to know that you can make your
program make decisions for you if you tell it what it needs to pay attention
to. An If Statement is a mechanism programmers have been using for quite some
time that will execute a block of code IF conditions are true.
For example,
you may want to print out "Is someone having a case of the Mondays?"
on your web site every Monday morning. Your If Statement would check to
see if the day was a Monday and if it was (true) then it would execute the code
to print out that annoying line of text.
VBScript If Statement: Syntax
In this
lesson we will be creating a simple VBScript If Statement that checks to
see if a number stored in the variable myNumber is equal to 7. If this
is true then it will execute a document.write function to print some
text to the browser.
VBScript Code:
<script
type="text/vbscript">
Dim myNumber
myNumber = 7
If myNumber = 7 Then
document.write("Lucky 7!")
End If
myNumber = 100343
If myNumber = 7 Then
document.write("You're a winner!")
End If
</script>
Display:
Lucky 7!
This example
show that in our first If Statement myNumber is indeed equal to 7 and
the block of code that prints out "Lucky 7!" is executed. However, we
then set myNumber equal to something that is not 7 (100343) and check with a
second If Statement and the block of code that should print out
"You're a winner!" is not executed.
The code
that resides within an if statement is only executed if the condition statement
of that If Statement is True.
VBScript If Statement: Else
Sometimes
you would like to have code executed with something is true and when
something is false. For example, if you wanted to wear a T-shirt if the
temperature was above 70 and a long-sleeved shirt if it was 70 or less. This
action to be taken if the conditional statement is false (that is, the
temperature is not above 70 degrees) is referred to in programming speak as the
Else clause of the If Statement.
If something
is true I want to do Code A, Else I want to do Code B.Below is the
implementation of our "what shirt to wear" problem.
VBScript Code:
<script
type="text/vbscript">
Dim temperature
temperature = 50
If temperature > 70 Then
document.write("Wear a T-Shirt!")
Else
document.write("Wear a long-sleeved shirt!")
End If
</script>
Display:
Wear a
long-sleeved shirt!
VBScript ElseIf
In the
previous lesson you learned how to create an If Statement and make use
of the Else clause. However, an If Statement is not always enough
for a programmer's needs.
VBScript ElseIf: Uses
The previous
lesson contained an example that let you execute one block of code if the
temperature was above a certain temperature and another block of code if it was
below a certain temperature. How would we check for another temperature range?
For this kind of programming solution you need to use the ElseIf
statement.
The basic
idea of the ElseIf statement is to create an If Statement within
another If Statement. This way you can check for many different cases in
a single If Statement clause.
Our
following example shows how you would check for two additional temperature
ranges to make our program more robust!
VBScript Code:
<script
type="text/vbscript">
Dim temperature
temperature = 65
If temperature > 70 Then
document.write("Wear a T-Shirt!")
ElseIf temperature
> 60 Then
document.write("Wear a hat!")
ElseIf temperature
> 50 Then
document.write("Wear a long-sleeved shirt!")
Else
document.write("Wear a coat!")
End If
</script>
Display:
Wear a hat!
Our
temperature was set to 65 and failed the first If Statement condition
because 65 is not greater than 70. However, on the first ElseIf Statement
we found that 65 was greater than 60 and so that block of code document.write("Wear
a hat!") was executed. Because there was a success the If Statement
then finishes and our VBSCript would begin again on the line of code following End
If
VBScript Select Case
The last two
lessons you have read through have covered the basics of using the If
Statement and the somewhat more advanced ElseIf Statement in
VBScript. This lesson will take it a step further by teaching you how to
implement the Select Case statement in VBScript.
VBScript Select Case: Why Use
It?
When you
need to check for many different cases on one variable you could create
a large number of ElseIf statements, but this is actually very
inefficient. Without getting to specific, it takes VBScript a great deal of
computing power to check all these different ElseIf statements. Also,
this kind of coding reduces human readability. Because of these problems
another programming method, the Select Case statement, was created to
solve this problem.
The downside
to this new method is you can only check if a variable is equal to something
"=" and not compare it with greater than, less than, etc (>, <,
>=, <=).
VBScript Select Case: Creation
A VBScript Select
Case statement can be summed up into three main parts.
- Variable
- The variable contains the value which we are trying to determine. Our
example will be a variable containing the name of a person.
- Case
Statements - The case statements contain the values we are checking for.
Our example will contain a few names, each their own case statement.
- Case
Code Blocks - Each case statement has a block of code associated with it.
When its case statement is True then the block of code is executed. Our
example will print out a greeting depending on the person's name.
Below is a
simple example of a Select Case statement that will write something
different to the web browser depending on the name stored in the variable myName.
VBScript Code:
<script
type="text/vbscript">
Dim myName
myName = "Charles"
Select Case myName
Case "Bob"
document.write("Been busy Bob?")
Case "Sara"
document.write("Seen any slick sunglasses Sara?")
Case "Charles"
document.write("Did you chuck your chowder Charles?")
End Select
</script>
Display:
Did you
chuck your chowder Charles?
VBScript Select Case: Else
Case
Just like an
If Statement has an optional Else clause, a Select Statement
has an optional Else case. When the variable cannot match any of the
cases included then the Else case will be used.
VBScript Code:
<script
type="text/vbscript">
Dim myName
myName = "supercalifragilisticexpialidocious"
Select Case myName
Case "Bob"
document.write("Been busy Bob?")
Case "Sara"
document.write("Seen any slick sunglasses Sara?")
Case "Charles"
document.write("Did you chuck your chowder Charles?")
Case Else
document.write("Who are you?")
End Select
</script>
Display:
Who are you?
VBScript Comments
Comments are
used to leave yourself notes or to mark a piece of code so that it doesn't get
executed. In VBScript the comment system is extremely simple because there is
only one kind of comment.
VBScript Comment: Single Line
Comment
VBScript
only has support for single line comments, so commenting out large blocks of
code or leaving yourself long notes can be quite a bit of work. The apostrophe
is the special character VBScript uses as its comment initiator.
The comment
in VBScript works by making the VBScript interpreter ignore everything to the
right of the apostrophe until a newline is reached. The following example shows
how to leave yourself notes and how you would comment out pieces of code you
don't want executed.
VBScript Code:
<script type="text/vbscript">
Dim myMessage
'myMessage = "I am
having a great day!"
myMessage = "I could use a
nap..."
'This will print out
myMessage to the visitor
document.write(myMessage)
</script>
Display:
I could use
a nap...
Commenting
out segments of code is often quite beneficial when you are trying to debug
your VBScript code. Leaving yourself notes in your VBScript is also a good
programming practice, as it will remind you of the code's purpose months or
even years later when you might be reviewing the code for the first time in a
long time.
VBScript For Loop
A For
Loop is used for special situations when you need to do something over and
over again until some condition statement fails. In a previous lesson, VBScript
Arrays we used a For Each loop to print out every item in our VBScript
array.
The For
Loop and the For Each Loop are very useful if you know how to use
them. This lesson will teach you the basics of each type of for loop.
VBScript For Loop
VBScript For
Loops are a little different compared to conventional for loops you see in
programming languages like C++ and Java, so pay extra close attention! The For
Loop has a counter variable that is created specifically to keep track of how
many times the loop's code has been executed. After each successful execution
of the loop VBScript automatically adds 1 to this counter variable and keeps
doing this until the MAX is reached.
Here is the
pseudo code for a VBScript For Loop:
- For counterVariable = 0 to MAX
You would
replace counterVariable with the name of your counter (most often
counter variable used is i). MAX would also be replaced with an
integer to specify how many times you would want the For Loop's code
executed.
VBScript For Loop Example
To clearly
illustrate how a For Loop works in the real world, the following example
will print out the counter variable to the browser after each successful loop.
VBScript Code:
<script
type="text/vbscript">
For count =
0 to 3
document.write("<br />Loop #" & count)
Next
</script>
Display:
Loop #0
Loop #1
Loop #2
Loop #3
You can see
here that the loop executes 4 times, once for 0, 1, 2 and 3.
VBScript For Each Loop
VBScript For
Each Loop is useful when you want to go through every element in an array,
but you do not know how many elements there are inside the array.
The
following example creates an array and then prints out every element.
VBScript Code:
<script
type="text/vbscript">
Dim myCloset(2)
myCloset(0) = "Coat"
myCloset(1) = "Suit"
myCloset(2) = "Boxes"
document.write("In my closet
is:")
For Each item In myCloset
document.write(item & "<br />")
Next
</script>
Display:
In my closet
is:Coat
Suit
Boxes
VBScript While Loop
A While
Loop is a simple loop that keeps looping while something is true.
Everytime it loops the block of code that is contained within the while loop is
executed. The while loop is controlled by the same kind of conditional
statement that you would see in an VBScript If Statement, so if you already
know how an If Statement words, this lesson will be a breeze!
VBScript While Loop Example
In this
lesson we will be creating a simple countdown that starts at 10 and ends with a
BANG! First, we need to decide what our condition statement will be.
Because we are counting down, it only seems logical that we would want our
countdown variable to be greater than 0, otherwise we should be having a BANG!
The
following code creates the while loop to create a simple VBScript countdown.
VBScript Code:
<script
type="text/vbscript">
Dim counter
counter = 10
While counter > 0
document.write(counter)
document.write("<br />")
counter = counter - 1
Wend
document.write("BANG!")
</script>
Display:
10
9
8
7
6
5
4
3
2
1
BANG!
The loop
starts with the counter variable equal to 10 and subtracts one from counter
each time through the loop. After 10 times(iterations) through the loop the
conditional statement counter > 0 fails and the the while loop ends (Wend).
VBScript Functions
When you are
programming in VBScript and other languages you may find that you have to
program the same code over, and over, and over. This is usually a sign that you
should be using a function to reduce this code repetition. Besides that,
functions are also useful to increase code readability (when done right).
Nearly all
the programs that you write will benefit from functions. Whether you use the
pre-made functions like document.write() or make your own it is a
necessity for any programmer to have a basic understanding of how functions
work in VBScript.
VBScript Function Creation
Let's start
off with a really simple example to show the syntax for creating a function.
The function myAdd will take two numbers and print out the result.
VBScript Code:
<script
type="text/vbscript">
Function myAdd(x,y)
myAdd =
x + y
End Function
'Let's use our function!
Dim result
result = myAdd(10,14)
document.write(result)
</script>
Display:
24
This may not
look that complex, but there is actually quite a lot going on this simple
example. We first created our function myAdd, which takes two arguments x
and y. These two arguments are added together and stored into the myAdd
variable.
When our
VBScript code executes it first stores the function for later use, then reaches
result = myAdd(10,14). VBScript then jumps to the function myAdd with
the values x = 10 and y = 14.
Notice that
the variable that we store our result in is the same as the function
name myAdd. This is on purpose. In VBScript you can only return a value
from a function if you store it inside a variable that has the same name
as the function.
After the
function has completed executing its code the line result = myAdd(10,14)
is now result = 24 where result is set equal to the the result of
the myAdd function. We then print out the value of result which
is 24.
We recommend
that you play around with creating VBScript functions for a while to get a
better feel for this important programming technique.
VBScript Date Functions
This
tutorial will teach you how to use VBScript's Date function and VBScript's Date
Format Functions. Both of these functions are included with VBScript. Note:
You will need to be running Internet Explorer to see the displays in this
tutorial. This is because VBScript is a Microsoft only scripting language.
VBScript Date Function
The VBScript
Date function is used to create the current date based off of the visitor's
system time. This means that if a user from China and a visitor from America
visit your site at the same time they will see their own local time displayed.
This example
shows how you would get the current date, store it into a variable and print it
to the browser.
VBScript Code:
<script
type="text/vbscript">
Dim myDateString
myDateString = Date()
document.write(myDateString)
</script>
Display:
Note: You will only see the Display if you are viewing this web page
with Internet Explorer.
VBScript FormatDateTime
Function
If the above
VBScript Date Format is not to your liking you can use the format constants of
the FormatDateTime function to customize your Date display. VBScript has
3 constants that relate to the Date function:
- 0 -
Default setting. You can see this in the example above.
- 1 - A
long date defined by the computer's regional settings.
- 2 - A
short date defined by the regional settings.
We will be
formatting the current date with these options, but you can also format static
dates (i.e. January 1, 1500) by replacing Date() with your own date
string.
VBScript Code:
<script
type="text/vbscript">
Dim myDateString0, myDateString1,
myDateString2, break
myDateString0 =
FormatDateTime(Date(), 0)
myDateString1 =
FormatDateTime(Date(), 1)
myDateString2 =
FormatDateTime(Date(), 2)
break = "<br />"
document.write(myDateString0 &
break)
document.write(myDateString1 &
break)
document.write(myDateString2 &
break)
</script>
Display:
Note: You will only see the Display if you are viewing this web page
with Internet Explorer.
VBScript MsgBox
If you are
using Internet Explorer then you would have received a popup as soon as you
came to this site. That was a VBScript MsgBox (message box), a popup window
that can be called using the MsgBox function. You can use this popup to
display crucial information, gather data, or just annoy your visitors!
VBScript MsgBox Creation
To create a
simple message box you only need to supply the MsgBox function with a
string and this will be what is displayed on the popup prompt. Our following
example will popup with the message "Hello There!".
VBScript Code:
<script type="text/vbscript">
MsgBox "Hello There!"
</script>
This is the
code for the popup box you see when you load this page.
VBScript MsgBox Arguments
While it is
quite easy to create a MsgBox with a simple message, customizing your MsgBox is
quote complex. There are up to 4 optional arguments you can give the MsgBox
function bringing the grand total to 5 arguments!
However,
only two of these options are that useful and they are:
- Button
(Integer)- Allows you to set which buttons will be displayed on your
popup. OK button is the default setting.
- Title
(String)- Sets the title of the popup window, much like the HTML title tag
sets the title of the browser window.
A complete
listing of the button constants can be found at Microsoft's VBScript Reference.
In this example
we will be creating a HTML button that creates a MsgBox with a message, a title
and an OK and Cancel button when clicked. For a review on HTML Buttons see our
VBScript Code:
<script
type="text/vbscript">
Function myPopup_OnClick()
MsgBox "Hello there!", 1, "Greeting Popup"
End Function
</script>
<form>
<input type="button"
value="Click Me!" name="myPopup" />
</form>
Display:
CLICK ME
0 comments:
Post a Comment