Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Schongar P.VBScript unleashed.1997

.pdf
Скачиваний:
46
Добавлен:
23.08.2013
Размер:
1.59 Mб
Скачать

<HR COLOR="BLUE">

<INPUT TYPE="SUBMIT" NAME="Btn1" VALUE="Item 1"><BR>

<INPUT TYPE="SUBMIT" NAME="Btn2" VALUE="Item 2"><BR>

<INPUT TYPE="SUBMIT" NAME="Btn3" VALUE="Item 3"><BR>

<INPUT TYPE="SUBMIT" NAME="Btn4" VALUE="Item 4"><BR>

<INPUT TYPE="SUBMIT" NAME="Btn5" VALUE="Item 5"><BR>

<SCRIPT LANGUAGE="VBScript">

<!--

Option Explicit

Dim MyList(4)

MyList(0)="Corn"

MyList(1)="Carrots"

MyList(2)="Peas"

MyList(3)="Chicken"

MyList(4)="Cake"

Sub Btn1_OnClick

Dim Item

Item=MyList(0)

ShowMessage(Item)

End Sub

Sub Btn2_OnClick

Dim Item

Item=MyList(1)

ShowMessage(Item)

End Sub

Sub Btn3_OnClick

Dim Item

Item=MyList(2)

ShowMessage(Item)

End Sub

Sub Btn4_OnClick

Dim Item

Item=MyList(3)

ShowMessage(Item)

End Sub

Sub Btn5_OnClick

Dim Item

Item=MyList(4)

ShowMessage(Item)

End Sub

Sub ShowMessage(SelItem)

MsgBox SelItem,0,"Item picked"

End Sub

-->

</SCRIPT>

</BODY>

</HTML>

You can also create multidimensional arrays. A 2-D array is declared like this:

Dim MyArray(4,9)

This declaration creates a table containing five rows and 10 columns. You can pull a particular value from the array using MyArray(row,column). The upper limit for multidimensional arrays is 60 dimensions.

One final note on arrays: You can declare what are called dynamic arrays that change sizes as the script is run. To declare a dynamic array, use the Dim or ReDim statement without adding a size value to the array name:

Dim MyDynamicArray()

To use this array, you would ReDim the array, adding a size value to the name:

ReDim MyDynamicArray(14)

You can ReDim an array as many times as needed.

Naming Conventions

The names that you give variables in VBScript are the same as for any other named item in a script. Variable names must begin with an alphabetical character:

'This is Ok

Dim MyVariable

'This is not Ok

Dim @Variable

In addition, variables cannot contain embedded periods and are limited to 255 characters. Finally, you cannot use the same name for two different values in the same scope. It's okay to have the same variable name declared in many different procedures, but the same variable name cannot be declared globally, and it cannot be declared twice in the same procedure.

When you declare variables, you should consider a few naming conventions. Table 2.1 lists these conventions.

Table 2.1. Naming conventions in VBScript.

Variable Subtype

Prefix

Boolean

bln

Byte

byt

Date

dtm

Double

dbl

Error

err

Integer

int

Long

lng

Object

obj

Single

sng

String

str

To use these naming conventions properly, you need to know the probable data subtype of the variables you declare. To name a variable that you know will contain a string, use the prefix along with a descriptive name for the variable:

Dim strName

The same rules follow for values that you know will be of a specified subtype:

Dim dblMiles

Dim blnEmpty

Dim intTotal

Using a convention such as this can save you time in the long run. It's much easier to see that you're about to make a mistake when you see an equation like strValue + dblMiles than if you simply saw Value + Miles.

The scope of a variable also has a naming convention. If you have a script-level variable, you can add an s to the prefix:

Dim sdblMyNumericValue

We'll talk more about coding conventions throughout the book. As new conventions are introduced, they will be incorporated into the sample code.

Constants

A constant is a named value that doesn't change throughout a script. For example, the value of the speed of light through room-temperature air at sea level is about 760 miles per hour. To use this constant in a script, you simply declare it, assign it, and use it like a variable. To differentiate a value that you want to be a constant in your script, you should use your own naming conventions, so that you don't try to reassign the value of the constant that you've created.

'vbSOL Speed of Light

Dim vbSol

vbSol = 760

Once you set the value of the constant, you can use it in your script as if it were the actual number. Keep in mind though that constants in VBScript are essentially just variables that you don't change in your program. Unlike other languages that allow you to set the value of a constant to static, there's no way to make a variable in VBScript unchangeable.

Program Flow

Program flow has to do with how your program moves from one line or procedure to another. To illustrate the flow of a program, many programmers use a flowchart.

The specifics of program flow have mostly to do with decision-making in scripts. Next, we'll talk about decision-making steps in VBScript and how different conditional and looping statements affect your script.

Operators

Before we can talk about how flow control works in a program, you need to be familiar with the operators used in the logic operations that control flow. Most of these will be familiar to you if you have a rudimentary background in math. Others might not be quite as obvious.

Table 2.2 contains the operators you can use in VBScript programs.

 

Table 2.2. VBScript operators.

Operator

Purpose

+

Addition

And

Logical And

&

Concantation operator

/

Division

Eqv

Logical Equivalence

^

Exponential

Imp

Logical Implication

\

Integer Division

Is

Logical Is (Refer to same object)

Mod

Modulus Operator (Remainder)

*

Multiplication

-

Negation and Subtraction

Not

Logical Not

Or

Logical Or

Xor

Logical Xor

You'll be using some of the logic operators in the next sections. The mathematical operators are used for math operations and, in some cases, concatenation. For example:

MyString = "Now is the time" & " for all good men..."

is functionally equivalent to

MyString = "Now is the time" + " for all good men..."

Decision-Making in Programs

Decision-making in programs is what programming is all about. Keep in mind that computers aren't really that good at thinking things through. You have to tell the program what to do every step of the way. Humans use a method of thinking that has what are known as fuzzy logic characteristics. If you were to ask more than one person to name the color of a particular scarf, you might get the answers red, pink, orange, and scarlet. If you ask a computer to name the color of an element on the screen, you'll get back the exact color name. Taking it one step further, if you ask the same group of people if the scarf is red, they all might answer "Yes." If you ask a computer if the screen element is red, it will return a yes value only if the item is exactly red.

Always keep in mind the limitations of the machine. Write good questions and you'll get good answers.

If...Then...Else

The If...Then...Else statement is one of the basic capabilities of a computer language. This statement tests for the truth of a statement and, depending on the answer, processes information or moves on to another piece of code. Let's look at an example of an If...Then...Else statement in a program (see Listing 2.5) and then talk about what's happening in the code.

Listing 2.5. If...Then...Else in a VBS script.

<HTML>

<HEAD>

<TITLE>Tester Page</TITLE>

</HEAD>

<BODY>

<H1>Tester Page for VBScript</H1>

<HR COLOR="BLUE">

<CENTER>

<FONT COLOR=RED SIZE=5>Question:</FONT><BR>

<FONT COLOR=BLUE SIZE=6>Who is buried in Grant's tomb?</FONT><BR>

<INPUT TYPE="SUBMIT" NAME="Btn1" VALUE="Click to test the code">

<INPUT TYPE="TEXT" NAME="Txt1">

</CENTER>

<SCRIPT LANGUAGE="VBSCRIPT">

<!--

Sub Btn1_OnClick()

Dim Message

If Txt1.Value = "Grant" then

Message="You're right!"

Else

Message="Try again"

End If

MsgBox Message, 0,"Tester Result"

End Sub

-->

</SCRIPT>

</BODY></HTML>

The example in Listing 2.5 is simple yet powerful. First of all, it's our first useful program. We answer a question, and the computer tells us if we are right or wrong. Immediate feedback and interaction are what it's all about. Let's break down the Btn1_OnClick procedure to see what's happening up close.

When Btn1 is clicked, the If...Then...Else statement asks if the value of the Txt1 text input box is Grant. If the answer to that question is true, the program sets the value of the variable Message to You're right. (See Figure 2.5.) If the answer is false, the value of Message is set to Try again. Notice that there is absolutely no room for error when answering this question. If the user enters grant, GRANT, or US Grant, the program will skip to the Else part of the program, and the message will be "Try again." Later you'll learn how to make If...Then...Else statements a little more tolerant.

Figure 2.5 : Outcome of a quiz answer.

If you have a simple If...Then statement, the statement can be just a single line:

If x=4 then y=12

When the statement takes more than one line, you need to close it off with an End If statement.

For...Next

The For...Next statement is used to run a block of code statements a certain number of times:

Dim x

For x = 1 to 10

Edit1.Value = x

Next

In this example, the counter starts at 1 and repeats Edit1.Value = x 10 times. You can also specify the way that the

value of x is counted, using the Step keyword. You can use an If...Then statement to exit the loop, if necessary:

Dim x

For x = 5 To 50 Step 5

Edit1.Value=x

If x > 20 Then Exit For

Next

In this case, the counter starts at 5 and stops at 50 for a total of 10 iterations. The loop is exited after five iterations, because x is greater than 20.

You could also use the Step value to count down, using negative numbers. Starting with a higher number and counting down to a lower one would look something like this:

Dim x

For x = 10 to 1 Step -1

Edit1.Value = x

Next

Do...Loop

Another common looping statement is Do...Loop. A Do...Loop statement is usually better to use than a For...

Next and Exit For combination. The Do...Loop statement allows you to create a loop that runs an infinite number of times. You need to be careful when using this statement-you don't want to accidentally get your script into a loop that it can't get out of:

Dim x

x=1

Do Until x = 25

x = x + 1

Loop

In this example, the place where you need to be careful is in Do Until x = 25. If the initial value of x was 30, the code would loop continuously without the x = 25 value ever being met.

There are two ways to test for a true value in the Do...Loop statement. You can use the Until keyword to repeat the loop until a condition is true or the While keyword to repeat while the condition is true:

Dim x

x = 10

Do While x < 100

x = x + 10

Loop

By placing the While or Until keyword after the Loop statement, you can make sure that the code inside the loop is run at least once:

Dim x

x = 1

Do

x = x + 1

If x > 30 Then Exit Loop

Loop Until x = 30

The code in this Do...Loop block is run at least once before it's ended. We've also added a safety feature in the form of an Exit Loop command that's issued if x is found to be greater than 30. If x is greater than 30, there is no chance that the value will ever be 30.

For Each...Next

The For Each...Next loop is used like the For...Next loop. It is used to test conditions in collections of objects. Objects have properties that are specified by keywords that are appended to the object name after a period. If I had an object with the property of color, you could access that property with MyObject.Color. Groups of objects are called collections, and you can test each of the objects for the truth of a statement using For Each...Next:

For Each Car in Lot

if Car.Color = "Red" then

MsgBox "Red car!", 0, "Answer"

End If

Next

In this example, the collection of objects is called Lot, and the objects are of the type Car. We go through the cars in the lot, and when we get to a red one we see a message. You'll learn more about objects in Part II of this book.

While...Wend

According to Microsoft, While...Wend is included in VBScript for those programmers who are familiar with its usage, but it's not well documented. Microsoft recommends using Do...Loop instead, but let's take a quick look at the While...Wend statement to become familiar with its usage:

Dim x

x = 1

While x < 10

x = x + 1

Wend

The While...Wend statement repeats until the value of the While portion of the statement is true.

Review

In this chapter, we talked about the differences between Visual Basic and VBScript. You learned that a script is a set of instructions that control the behavior of objects in your Web pages. You learned about data types and that all variables in VBScript are variants. Finally, you learned about program flow and the statements used to loop through a program.