Monday, February 7, 2011

Lesson 2-Working with Variables

A variable is a named location in computer memory that you can use for storage of data during the execution of your scripts. You can use variables to:
  • Store input from the user gathered via your web page
  • Save data returned from functions
  • Hold results from calculations

An Introduction to Variables

Let's look at a simple VBScript example to clarify the use of variables.
Sub cmdVariables_OnClick
  Dim Name
  Name = InputBox("Enter your name: ")
  MsgBox "The name you entered was " & Name
End Sub
The first line of this example defines a sub procedure associated with the click event of a command button named cmdVariables.
On the second line we declare a variable named Name. We are going to use this variable to store the name of the user when it is entered. The third line uses the InputBox function to first prompt for, and then return, the user's name. You will see more of the InputBox function later in this tutorial. The name it returns is stored in the Name variable.
The fourth line uses the MsgBox function to display the user's name. Finally, the sub procedure completes on line five.
Exactly how, and where, variables are stored is not important. What you use them for, and how you use them is important. That is what we will be looking at next.

Declaring Variables

There are two methods for declaring variables in VBScript, explicitly and implicitly. You usually declare variables explicitly with the Dim statement:
Dim Name
This statement declares the variable Name. You can also declare multiple variables on one line as shown below, although it is preferable to declare each variable separately:
Dim Name, Address, City, State
Variables can be declared implicitly by simply using the variable name within your script. This practice is not recommended. It leads to code that is prone to errors and more difficult to debug.
You can force VBScript to require all variables to be explicitly declared by including the statement Option Explicit at the start of every script. Any variable that is not explicitly declared will then generate an error.

Variable Naming Rules

When naming variables the following rules apply:
  • They must begin with an alphabetic character
  • They cannot contain embedded periods
  • They must be unique within the same scope. There is more on scopes later in this lesson
  • They must be no longer than 255 characters

Variants and Subtypes

VBScript has a single data type called a variant. Variants have the ability to store different types of data. The types of data that a variant can store are referred to as subtypes. The table below describes the subtypes supported by VBScript.
 
SubtypeDescription of Uses for Each Subtype
ByteInteger numbers between 0 to 255
BooleanTrue and False
CurrencyMonetary values
DateDate and time
DoubleExtremely large numbers with decimal points
EmptyThe value that a variant holds before being used
ErrorAn error number
IntegerLarge integers between -32,768 and 32,767
LongExtremely large integers (-2,147,483,648 and 2,147,483,647)
ObjectObjects
NullNo valid data
SingleLarge numbers with decimal points
StringCharacter strings

Assigning Values

You assign a value to a variable by using the following format:
Variable_name = value
The following examples demonstrate assigning values to variables:
Name = "Larry Roof"
HoursWorked = 50
Overtime = True

Scope of Variables

The scope of a variable dictates where it can be used in your script. A variable's scope is determined by where it is declared. If it is declared within a procedure, it is referred to as a procedure-level variable and can only be used within that procedure. If it is declared outside of any procedure, it is a script-level variable and can be used throughout the script.
The example below demonstrates both script-level and procedure-level variables.
<SCRIPT>
  Dim counter
  Sub cmdButton_onClick
    Dim temp
  End Sub
</SCRIPT>
The variable counter is a script-level variable and can be utilized throughout the script. The variable temp exists only within the cmdButton_onClick sub-procedure.

Constants

VBScript does not provide support for constants, such as you find in other programming languages. You can work around this by assigning values to variables that you have defined as shown in the example below. Here, TAX_RATE is our constant.
<SCRIPT>
  Dim TAX_RATE
  TAX_RATE = .06
  Function CalculateTaxes
    CalculateTaxes = CostOfGoods * TAX_RATE
  End Function
</SCRIPT>

Arrays

The VBScript language provides support for arrays. You declare an array using the Dim statement, just as you did with variables:
Dim States(50)
The statement above creates an array with 51 elements. Why 51? Because VBScript arrays are zero-based, meaning that the first array element is indexed 0 and the last is the number specified when declaring the array.
You assign values to the elements of an array just as you would a variable, but with an additional reference (the index) to the element in which it will be stored:
States(5) = "California"
States(6) = "New York"
Arrays can have multiple dimensions-VBScript supports up to 60. Declaring a two dimensional array for storing 51 states and their capitals could be done as follows:
Dim StateInfo(50,1)
To store values into this array you would then reference both dimensions.
StateInfo(18,0) = "Michigan"
StateInfo(18,1) = "Lansing"
VBScript also provides support for arrays whose size may need to change as the script is executing. These arrays are referred to as dynamic arrays. A dynamic array is declared without specifying the number of elements it will contain:
Dim Customers()
The ReDim statement is then used to change the size of the array from within the script:
ReDim Customers(100)
There is no limit to the number of times an array can be re-dimensioned during the execution of a script. To preserve the contents of an array when you are re-dimensioning, use the Preserve keyword:
ReDim Preserve Customers(100)

 In this exercise we will create a page that performs a simple calculation involving sub-totals, sales tax and final totals. Follow the step-by-step instructions that will introduce you to using variables with VBScript. In this exercise you will create an HTML document which contains a script that will retrieve data from a web page, perform calculations and output a result.

Creating the HTML Document

A completed copy of this part of the exercise can be found in the file exer2_v1.html.
Open up a text editor and insert the following HTML code:
<HTML>
<HEAD>
<TITLE>Working With VBScript: Exercise 2</TITLE>
</HEAD>
<BODY>
<H1>Your Second VBScript Exercise</H1>
<P> Variables can be used to store and manipulate values. To 
see a demonstration of this enter a quantity and unit price 
in the fields below and click the "Calculate Cost" button.</P>
<FORM NAME="frmExercise2">
  <TABLE>
    <TR>
      <TD><B>Quantity:</B></TD>
      <TD><INPUT TYPE="Text" NAME="txtQuantity" SIZE=5></TD>
    </TR>
    <TR>
      <TD><B>Unit price:</B></TD>
      <TD><INPUT TYPE="Text" NAME="txtUnitPrice" SIZE=5></TD>
    </TR>
  </TABLE>
  <BR>
  <INPUT TYPE="Button" NAME="cmdCalculate" VALUE="Calculate Cost">
</FORM>
</BODY>
</HTML>
Save the file, and load it into Internet Explorer. The result is shown below.
Your Second VBScript Exercise

Adding VBScript

In this part we will be adding a script to provide functionality for when the Calculate Cost command button is clicked. A completed copy of this part of the exercise can be found in the file exer2_v2.html.
Re-open the HTML document that you created in part 1, if necessary. Modify the document adding the scripting lines as shown by the shading:
Please note that the apostrophes " are there to comment out code - there is more on this on the next page - and the _at the end of the line Subtotal = document.frmExercise2.txtQuantity.value_ is a coding convention which is telling you to type the following line on the same line as this one and to discard the _.
<HTML>
<HEAD>
<TITLE>Working With VBScript: Exercise 2</TITLE>
<SCRIPT LANGUAGE="VBScript">
<!-- Add this to instruct non-IE browsers to skip over VBScript modules.
Option Explicit
Sub cmdCalculate_OnClick
  Dim AmountofTax
  Dim CRLF
  Dim Message
  Dim Subtotal
  Dim TABSPACE
  Dim TAX_RATE
  Dim TotalCost
' Define our constant values.
  TAX_RATE = 0.06
  CRLF = Chr(13) & Chr(10)
  TABSPACE = Chr(9)
' Perform order calculations.
  Subtotal = document.frmExercise2.txtQuantity.value _
           * document.frmExercise2.txtUnitPrice.value
  AmountofTax = Subtotal * TAX_RATE
  TotalCost = Subtotal + AmountofTax
' Display the results.
  Message = "The total for your order is:"
  Message = Message & CRLF & CRLF
  Message = Message & "Subtotal:" & TABSPACE & "$" & Subtotal & CRLF
  Message = Message & "Tax:" & TABSPACE & "$" & AmountofTax & CRLF
  Message = Message & "Total:" & TABSPACE & "$" & TotalCost
  MsgBox Message,,"Your Total"
End Sub
-->
</SCRIPT>
</HEAD>
<BODY> 
...
  • Save the file and test it by loading it into Internet Explorer. Enter 100 into the Quantity field and 10 into the Unit Price field. Try out the Calculate Cost button. The result is shown below:
Exercise 2

 What should be obvious right from the start is that this script is far more involved than the one used with Exercise 1. Don't be intimidated by its size. As with the previous lesson, we will work through this script line-by-line.
After the starting <SCRIPT> tag and HTML comment we find:
Option Explicit
Do you remember what this statement does? It forces you to declare all of your variables.
Next we create a sub procedure for the click event of the cmdCalculate button.
Sub cmdCalculate_OnClick
Following that we declare seven variables, three of which we are going to use as constants. They can be identified by the fact that they are all in uppercase. In VBScript, case doesn't matter (though it does in JavaScript). We are using it to make the script easier to read. Are the variables procedure-level or script-level variables? They are procedure-level since they are declared within a procedure.
In VBScript, anything after an apostrophe is a comment. As such, they are ignored when the script is processed. Comments can appear on a line by themselves or at the end of a line of script. Comments at the end of a line are referred to as inline comments.
' Define our constant values.
The constants are assigned values in the following lines. Chr() is a VBScript function that returns the character associated with a specified ASCII code. ASCII codes 13, 10 and 9 are carriage return, line feed and tab, respectively.
CRLF = Chr(13) & Chr(10)
TABSPACE = Chr(9)
The next line demonstrates how values are taken from a form on a web page, and used within a script. The two fields on our form were named txtQuantity and txtUnitPrice in their HTML <INPUT> tags. The form was named frmExercise2. Here we are referencing our web document, then the form, then the input field and finally the value of that field. The value associated with each field contains what the user entered into that field on the web page. The * says to multiply the value of the first field, txtQuantity, by the second field, txtUnitPrice.
Note
The commonly used VBScript operands are + for addition, - for subtraction, * for multiplication and / for division.
The result of this calculation is then stored in the variable Subtotal. Next we perform some additional calculations. Finally, we display the result of our calculations using the MsgBox function. The ampersand character, &, is used to concatenate two strings.
As with the previous lesson, don't get too worried about understanding all of the details of this example right now. As you continue to work with VBScript you will begin to "pickup" the language.

Summary

That completes Exercise 2. You just created a web page that interacts with the user to gather data, perform calculations and present results-the fundamental components of most applications. Along the way you have learned:
  • The types of variables that VBScript supports
  • How to declare and use variables within a script
  • A technique to work around the absence of constants in VBScript
  • What a comment line is in a script
In the next lesson we will look at objects. You will learn what they are and how they are used with VBScript.

How It Works

Your Second VBScript Exercise

No comments:

Post a Comment