What is VBScript?
What is VBScript?
VBScript (Visual Basic Script) is a scaled down version o
VBScript (Visual Basic Script) is a scaled down version o f Visual Basic. Visual Basic is a fullf Visual Basic. Visual Basic is a full blown programming language. VBScript, on the other hand, is a scripting language that can be blown programming language. VBScript, on the other hand, is a scripting language that can be
run client-side (i.e. via your web
run client-side (i.e. via your web browser), or server-side (i.e. on the web server). VBScript is thebrowser), or server-side (i.e. on the web server). VBScript is the most common scripting language on websites that use
most common scripting language on websites that use ASP (Active Server Pages).ASP (Active Server Pages). When VBScript is run on t
When VBScript is run on the client side, the user's browser needs to support he client side, the user's browser needs to support VBScript. When runVBScript. When run on the server side, the server needs t
on the server side, the server needs to support it. In this tutorial, our VBScript examples are oo support it. In this tutorial, our VBScript examples are o nn the client-side, therefore, in order to g
the client-side, therefore, in order to get the most out of this tutorial, you should use Internetet the most out of this tutorial, you should use Internet Explorer, as most other browsers don't support VBScript.
Explorer, as most other browsers don't support VBScript.
What do I need to create VBScript?
What do I need to create VBScript?
You can creatYou can create JavaScript using the same equipment you ue JavaScript using the same equipment you use when creating HTML. That se when creating HTML. That is:is:
y
y CComputer omputer y
y Text editor. For example, NotText editor. For example, Notepad (for Windows), Pico (for Linux), or Simpletext (Mac).epad (for Windows), Pico (for Linux), or Simpletext (Mac).
You could use a
You could use a VBScript editor if you like but VBScript editor if you like but it's not needed. The next lesson willit's not needed. The next lesson will discuss some popular VBScript editors.
discuss some popular VBScript editors.
y
y Internet Explorer.Internet Explorer. NNote:ote: VBScript is not supported in most (if not all) other browsers -VBScript is not supported in most (if not all) other browsers
-therefore, it's recommended that you use
therefore, it's recommended that you use Internet Explorer.Internet Explorer. In the next lesson, we'll see so
In the next lesson, we'll see so me popular VBScript editors.me popular VBScript editors. You don't necessarily need a
You don't necessarily need a special VBScript editor in order to special VBScript editor in order to code in VBScript - you couldcode in VBScript - you could just use a normal text editor.
just use a normal text editor. However, a special VBScript editor will probably make your However, a special VBScript editor will probably make your liflifee easier, and enable you to code your scripts much faster.
easier, and enable you to code your scripts much faster. If you'd prefer not to
If you'd prefer not to use a text editor, you can check use a text editor, you can check out these HTML / VBScript editors:out these HTML / VBScript editors:
y
y Text Hawk Text Hawk y
y EditPlusEditPlus y
y Adobe Dreamweaver Adobe Dreamweaver y
y HTML KitHTML Kit (Free)(Free)
OK, to be precise,
OK, to be precise, most VBScript editors aren't solelymost VBScript editors aren't solely VBScript VBScript editors. Often, they will beeditors. Often, they will be HTML editors with
HTML editors with VBScript support VBScript support . This generally means that t. This generally means that t hey will include syntaxhey will include syntax highlighting for VBScript (ability to recognise VBScript and co
highlighting for VBScript (ability to recognise VBScript and co lor code/format it for you). Itlor code/format it for you). It may also have a too
may also have a too lbar with options that are specific to VBScript. Given you lbar with options that are specific to VBScript. Given you will probably bewill probably be coding HTML at the same t
coding HTML at the same time, it makes sense to have an edime, it makes sense to have an ed itor with HTML support anyway.itor with HTML support anyway. Regardless of whether you have a
Regardless of whether you have a HTML / VBScript editor or HTML / VBScript editor or not, you still need to test your not, you still need to test your pages in a web browser.
pages in a web browser. As mentioned previously, Internet Explorer is your best bet As mentioned previously, Internet Explorer is your best bet for thisfor this when running VBScript on t
OK, so you've got yourself an editor? Let's move on and learn some VBScript!
What VBScript syntax refers to, is a set of rules that determine how the language w ill be written (by the programmer) and interpreted (by the browser or server).
The VBScript syntax is based on t he Visual Basic (VB) syntax. VB is a full blown programming environment and VBScript is a scaled down version of VB.
You may also find the VBScr ipt syntax similar to JavaScript in some ways. If you know JavaScript, or any other language for that matter, you will be familiar with terms such as
variable s, functions, st at ements, oper ators, d at a type s, objects etc. VBScript includes these too. Most of these will be covered throughout the rest of this tutorial. For now, we'll start with the basics.
Basic VBScript Code
Here's some basic VBScript that outputs some text to the browser. Again, if you know JavaScript, this will look familiar.
<script type="text/vbscript">
document.write("VBScript is similar to JavaScript, but different.") </script>
This results in:
VBScript is similar to JavaScript, but different.
Ex
planation of Code
y The <script> tags are actually HTML, and tell the browser to expect a script in between
them. You specify the language using thetype attribute. In this case, we're using
VBScript.
y The part that writes the actual text is only 1 line (document.write("VBScript is
similar to JavaScript, but different.")). This is how you write text to a web page in VBScript. This is an example of using a VBScript function (also known as
method ).
Concatenation
When writing large blocks of text to the screen, you may need to break your code up over many lines. To ensure this doesn't affect the output, you can use an underscore to indicate a
<script type="text/vbscript">
document.write("The VBScript syntax allows you to " &_ "concatenate multiple lines together, so that they " &_ "appear joined together seamlessly")
</script>
This results in:
The VBScript syntax allows you to concatenate multiple lines together, so that they appear joined together seamlessly
Where to Put Your Scripts?
You can place your scripts in any of the following locations:
y Between the HTML document'shead tags.
y Within the HTML document's body (i.e. between thebody tags). y Both of the above.
A variable is a fundamental part of any pro gramming language. Variables are best visualized as a container. This is because a variable's purpose is to hold something - a val ue.
How does the variable get the value? You, as a programmer, assign the value to it. This value could be dynamically produced, depending on your program/script.
Once the variable has a value, you can use subsequent code to check its value, and do something (or not do something) depending on its value.
Some programming languages require that you d eclar e your variable before assigning a value to it. Others (such as VBScript) make this optional. In any case, it is good practice to declare all your variables first.
D
eclare a VBScript Variable
VBScript variables are declared using the dimstatement: <script type="text/vbscript">
Dim firstName Dim age
</script>
These variables could also have been declared on the same line, separated by a comma:
<script type="text/vbscript"> Dim firstName, age
</script>
O
ption
Ex
plicit
As mentioned, it's good practice to declare all variables before using them. Occasionally, if you're in a hurry, you might forget to do this. Then, one day, you might misspell the variable name and all sorts of problems could start occurring with your script.
VBScript has a way of ensuring you declare all your variables. This is done with theO ption
Expl icit statement: <script type="text/vbscript"> Option Explicit Dim firstName Dim age </script>
A
ssign Values to your Variables
You assign values using an equals operator (equals sign). The variable name goes o n the left, the value on the right.
<script type="text/vbscript"> Option Explicit Dim firstName Dim age firstName = "Borat" age = 25 </script>
D
isplay your Variables
You can output the value of a variable by including it within thedocument.write() method. <script type="text/vbscript"> Option Explicit Dim firstName Dim age firstName = "Borat" age = 25
d ocument.write("Firstname: " & firstName & "</br />") d ocument.write("Age: " & age)
</script>
Display in Browser: Firstname: Borat Age: 25
A VBScript arr a y is a special type of variable that allows you to store multiple values against a single variable.
For example, say you have a shopping list that you want to store and write out to the screen. You could store these in a simple variable like this:
item1 = "Bananas" item2 = "Bread" item3 = "Pasta"
This will work fine. But one problem with this approach is that you have to write out each
variable name whenever you need to work with it. Also, you can't do things like, loop through all your variables. If these values were stored in an array, you could save yourself a lot of time.
What
D
oes an
A
rray Look Like?
Arrays can be visualized as a stack of elements. Each element has an index number (left column) and a value (right column).
Note that VBScript arrays start their numbering at zero.
Array
0 Bananas 1 Bread 2 Pasta
Creating
A
rrays in VBScript
VBScript arrays are created by first assigning an arra y object to a variable name...
Dim arrayName(numberOfElements)
then by assigning values to the array...
arrayName(0) = "Array element 1" arrayName(1) = "Array element 2" arrayName(2) = "Array element 3"
So, using our prior example, we could write:
Dim shoppingList(3)
shoppingList(0) = "Bananas" shoppingList(1) = "Bread" shoppingList(2) = "Pasta"
You can access data in an array by referring to the name of the array and the element's index number.
D
isplay a Single
Array
Element
This example displays the second element of the array named shoppingList (remember that VBScript array index numbers begin at zero). In this case, the value would be Br ead
document.write(shoppingList(1))
So, building on our previous example, you could use the following code to declare an array, assign values, then output the contents to the screen.
Dim shoppingList(3)
shoppingList(0) = "Bananas" shoppingList(1) = "Bread" shoppingList(2) = "Pasta"
document.write(shoppingList(1))
This results in: Bread
M
odify the Contents of an
A
rray
You can modify the contents of an array by specifying a value for a given index number:
shoppingList(1) = "Wholemeal Bread"
Now, the value of the second element will be: Wholemeal Bread
To display the date using VBScript, you use the VBScript d at e() function.
date()
VBScript
D
ate Code
To display this to the user, you need to output it like you would anything else - for example, using the document.writ e() method.
document.write(date())
localDate = date()
document.write(localDate)
Both these result in:
Note: If this is blank, your browser probably doesn't support VBScript. Try using Internet Explorer.
VBScript
D
ate Format
You can use the VBScript F or matDat eT ime() method to format the date to either a l ong date
format or a short date format.
The FormatDateTime() method accepts two arguments: The date being formatted, and the required format (indicated by a constant). The formats are specified as follows:
y 0 - This represents the default date format (as in the previous example)
y 1 - This represents the long date format (based on the user's regional settings) y 2 - This represents the short date format (based on the user's regional settings)
Long Format
To use long date format, you pass the F or matDat eT ime() an argument of 1. localDate = FormatDateTime(date(), 1)
document.write(localDate)
This results in:
Short Format
To use long date format, you pass the F or matDat eT ime() an argument of 2. localDate = FormatDateTime(date(), 2)
document.write(localDate)
This results in:
VBScript If statements are a handy tool for any VBScript programmer. In fact, If statements are a universal to all programming languages (that I'm aware of).
For example, you might have a website that asks the user what color their hair is. You could write code that only executes if their hair is say, black. OK, that's a prett y lame example but you get the idea!
Ex
ample If Statement
In this example, we'll stick with the lame subject of hair color, but to keep it simple, we won't ask for user input. We'll just set a variable with a hair color values.
<script type="text/vbscript"> Dim hairColor
hairColor = "Black"
If hairColor = "Black" Then
d ocument.write("Same color as my cat!")
End If
</script>
This results in:
Same color as my cat!
If
E
lse Statement
An If Else statement is an extension to t he If statement. This allows you to tell the progra m to do something else in the event t hat the condition is not true.
<script type="text/vbscript"> Dim hairColor
hairColor = "Blue"
If hairColor = "Black" Then
document.write("Same color as my cat!")
Else
d ocument.write("Oh well, whatever...")
End If </script>
This time the value of hair Color is blue. Because it is not black, the Else part of the state ment is
executed. This results in: Oh well, whatever...
E
lseif Statement
You can add an E l seif to test for another condition if you like. You could do as many of these as you like too.
<script type="text/vbscript"> Dim hairColor
hairColor = "Blue"
If hairColor = "Black" Then
document.write("Same color as my cat!")
Elseif hairColor = "Blue" Then
d ocument.write("Same color as my parrot!")
Else
document.write("Oh well, whatever...") End If
</script>
This time the 'Elseif' code is executed because the value of the ha ir Color variable is blue.
This results in:
Same color as my parrot!
In the previous lesson, we used an E lseif statement to perform multiple checks against the value of a variable. VBScript Select Case statements are a more efficient way of doing this.
A Select Case statement allows us to perform multiple tests, with less code (and less computing
power). This can be especially beneficial when you have many cases to test for.
Ex
ample Select Case Statement
<script type="text/vbscript"> Dim hairColor
hairColor = "Yellow"
Select Case hairColor Case "Black"
d ocument.write("Same as the cat")
Case "Blue"
d ocument.write("Same as the parrot")
Case "Yellow"
d ocument.write("Same as the canary")
Case Else
d ocument.write("Ah well, whatever...")
End Select
</script>
This results in: Same as the canary
Limitations of Select Case
Although the Select Case statement is more efficient than an If Elseif statement for this type of
thing, it is somewhat limited - there may be times that you need to use an If Elseif statement. For example, the Select Case statement only allows you to check if a variable is equal to a value
-you can't test to see if it is greater than, less than etc. Also, -you can only test against one variable. If you have multiple variables to test against, you'll need to use an If statement.
In VBScript (and virtually all other languages), " loops" enable your program to continuously execute a block of code for a given number of times, or while a given condition is true.
The VBScript While Loop executes codewhile a condition is true.
Ex
ample While Loop
This example displays a the value of a counter while the count is less than or equal to 8.
<script type="text/vbscript"> Dim hoursWorked
hoursWorked = 0
W hile hours W orked <= 8
d ocument.write("Hours worked : " & hours W orked ) d ocument.write("
")
hours W orked = hours W orked + 1 W end
document.write("Home time!") </script>
This results in: Hours worked: 0 Hours worked: 1 Hours worked: 2 Hours worked: 3 Hours worked: 4 Hours worked: 5 Hours worked: 6 Hours worked: 7 Hours worked: 8 Home time! Ex
lanation of code
1. We started by declaring a variable called "hoursWorked" and setting it to 0
2. We then opened a while loop and inserted our condition. Our condition checks if the current value of the hoursWorked variable is less than or equal to 8.
3. This is followed by code to execute while the condition is true. In this case, we are simply, outputting the current value of hoursWorked, preceded by some text. 4. We then increment the value by 1.
5. When the browser reaches the c losing curly brace, if the condition is still true, it goes back to the first curly brace and executes the code again. By now, the hoursWorked
variable has been incremented by 1. If the condition is not true (i.e. the variable is greater than 10), it exits from the loop, and continues on with the rest of the code.
The VBScript For Loop allows you to execute codefora given number of iterations. Using a For loop, you provide a given expression, and the loop will iterate for as long as that expression
results to true.
Ex
ample For Loop
Using the same scenario as the previous lesson, the loop will iterate from 0 to 8 . It will then continue processing the rest of the page.
<script type="text/vbscript">
For hours W orked = 0 to 8
d ocument.write("Hours worked : " & hours W orked ) d ocument.write("<br />")
Next
document.write("Home time!") </script>
This results in: Hours worked: 0 Hours worked: 1 Hours worked: 2 Hours worked: 3 Hours worked: 4 Hours worked: 5 Hours worked: 6 Hours worked: 7 Hours worked: 8 Home time!
For
E
ach Loop
The VBScript For Each Loop allows you to iterate over an array. This can be a quick and easy way of accessing all elements within an array without you needing to know how many elements are in it.
Dim shoppingList(3)
shoppingList(0) = "Bananas" shoppingList(1) = "Bread" shoppingList(2) = "Pasta"
For Each listItem In shoppingList d ocument.write(listItem)
d ocument.write("<br />")
Next
</script>
This results in: Bananas
Bread Pasta
In previous lessons, we've used the equa ls oper ator to assign a value to a variable. We've also used it to perform a test against a given condition (for example, the If statements).
In VBScript, operators are used to perform an operation. For example, an operator could be used to assign a value to a variable. An operator could also be used to compare two values.
Below is a listing of VBScript operators and a brief description of them. Don't worry if you don't understand all of them at this stage - just bookmark this page for reference and return whenever you need to.
A
rtithmetic
O
perators
Operator Description + Addition - Subtraction * Multiplication / Division\ Integer Division (divides two numbers and returns an integer result)
Mod Modulus (remainder of a division)
^ Exponentiation (raises the number to the power of an exponent)
A
ssignment
O
perator
Operator Description
Comparison
O
perators
Operator Description
= Is equal to
<> Is not equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
Logical
O
perators
Operator Description
And
Performs a logical conjunction on two expressions (if both expressions evaluate to True, result is True. If either expression evaluates to False, result is False)
Or Performs a logical disjunction on two expressions (if either or both expressions evaluate to True, result is True).
Not Performs logical negation on an expression.
Xor
Performs a logical exclusion on two expressions (if one, and only one, of the expressions evaluates to True, result is True. However, if either expression is Null, result is also Null).
Concatenation
O
perators
Operator Description
& Concatenate (join two strings together)
+ Adds two numbers together
VBScript functions are self contained blocks of code that perform a given "function", or task. Sometimes when coding, you may find yourself having to write the same piece of code over and over again. If this happens, chances are, you'd be better off writing a function. That way, you can write the code once, then simply call the function whenever you need it.
Creating VBScript Functions
VBScript functions are defined using the F unction and End F unction keywords. The code that
Here's the method for creating VBScript functions:
1. Start by using the F unction keyword. This tells the browser that a function is about to be
defined
2. Provide a name for the function (make it concise, but descriptive) 3. Follow the name with opening and closing brackets
4. Add the names of any arguments that the function requires (optional) 5. Starting on a new line, write the code that makes up the function 6. Finish with End F unction
Example:
Function sum(number1,number2) sum = number1 + number2 End Function
Calling VBScript Functions
A function doesn't actually do anything until it is called. Once it is called, it takes any arguments, then performs it's function (whatever that may be).
You call a VBScript function like this:
1. Write the function name, followed by opening and closing brackets 2. Between the brackets, provide all arguments that the function requires Example:
sum(100,9)
Combined - Creating, then Calling a VBScript Function
So, if we combine them together, and add a tiny bit more code, we might end up with something that looks like this:
<script type="text/vbscript">
Function sum(number1,number2)
sum = number1 + number2
End Function
Dim total
total = sum(100,9)
document.write(total) </script>
Using the above code, the following is produced: 109