One of the key concepts that you need to understand when working with VBScript, or any programming language, is how to store, retrieve, and modify data.. Specifically, you will learn how
Trang 1100 Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition
CH A L L E N G E S
1 Change the Math Game to use a different equation and modify the logic required
to adapt the statements that work with the WordPad and Calculator applications
2 Try using the SendKeys() method to work with other Windows applications, such
as Notepad
3 Spend some time reviewing VBScript built-in math functions and see if you can create a new calculator similar to the Square Root calculator.
4 Modify the VBScript template presented earlier in this chapter and adapt it to suit your personal preferences, and then use it as you begin developing new VBScripts.
Trang 2Constants, Variables, and
Arrays
4
This is the second of five chapters in this book that teaches the
funda-mentals of VBScript One of the key concepts that you need to understand when working with VBScript, or any programming language, is how to store, retrieve, and modify data This chapter will teach you a number of different ways to perform these tasks By the time you have completed this chapter, you will know how to write scripts that can collect and manipulate data Specifically, you will learn how to
• Process data passed to the script at execution time
• Store data that does not change
• Work with data that can change during script execution
• Process collections of related data as a unit
Project Preview:
The Story of Captain Adventure
In this chapter, you will learn how to create a game that builds a comical adven-ture story based on user input The game begins by collecting answers to a series
of questions without telling the user how the answers will be used After all the information that the script needs is collected, the story is displayed, as shown in Figures 4.1 through 4.7
Trang 3102 Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition
Figure 4.1
The story’s initial
splash screen.
Figure 4.2
The user is the
star of the story
Figure 4.3
The story begins
anywhere the
user specifies.
Figure 4.4
The user must
specify the object
that provides our
hero with his
superpowers.
Figure 4.5
The user specifies
the story’s
co-star.
Trang 4Through the development of this story-building game, you will learn a number of important programming techniques, including how to collect, store, and reference data In addition, you will learn how to control the presentation of script output
Understanding How Scripts View Data
VBScript, like other programming languages, needs a way of storing data so that it can be accessed throughout the execution of a script Up to this point in the book, you have seen a number of examples of how VBScript temporarily stores and references data Now I’ll explain how this works
VBScript supplies a number of different statements
that allow you to define several different types of data
These VBScript statements are outlined in Table 4.1
Figure 4.6
Finally, the user
specifies a
magic word.
Figure 4.7
After the script
has all the
information it
needs, the
story is told.
Definition
Data is information that a computer
program collects, modifies, stores, and retrieves during execution.
Trang 5The Conststatement is used to define data that never changes throughout the execution of
a script For example, in this book you will sometimes see constants used to define strings that are used to define a standard greeting message in pop-up dialog boxes The Dim
state-ment is used to define a variable A variable stores an individual piece of data such as a name,
number, or date The ReDim statement is used to create an array Arrays are used to store
groups of related information For example, instead of defining 20 different variables to store information about 20 different people, a single array could be defined and then infor-mation about each person can be stored in it Each of these statements will be examined in greater detail throughout the rest of this chapter
Working with Data That Never Changes
Data should be defined within a script according to the manner in which it will be used If the script only needs to reference a piece of data that has a value that is known during script development, then the data can be defined as a constant An example of a constant is the mathematical value of pi Other examples of constants include specific dates of history, the name of places, and so on
There are two sources of constants within scripts First, you can define your own constants within your scripts Another option is to reference a built-in collection of readily available constants provided by VBScript
Assigning Data to Constants
If you’re going to write a script and know for a fact that you need to reference one or more values that will not change during the execution of the script, then you can define each piece of data as a constant One of the nice features of constants is that, once defined, their
Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition
Dim Defines a VBScript variable or array
TA B L E 4 1 V B SC R I P T ST A T E M E N T S TH A T DE T E R M I N E
HO W DA T A IS DE F I N E D
Trang 6value cannot be changed This prevents their values from being accidentally modified dur-ing the execution of the script
If your script attempts to modify the value assigned to a constant after it has been initially assigned, you will see an “Illegal assignment: ‘XXXXXXXX’ ” error message when the script executes XXXXXXXX will reference the name of the constant Open your script and do a search on this word and look for the state-ments that have attempted to modify its value to find the source of the error
To define a constant within a VBScript, you must use the Const statement This statement has the following syntax:
[Public | Private] Const ConstName = expression
Publicand Privateare optional keywords and are used
to determine the availability of constants throughout
a script Defining a constant as Publicmakes it
avail-able to all procedures within the scripts Defining a
constant as Privatemakes it available only within the
procedure that defines them ConstNameis the name of
the constant being defined, and expression is the
value that identifies the data being defined To make
sense of all this, let’s look at an example
‘*************************************************************************
‘Script Name: LittlePigs.vbs
‘Author: Jerry Ford
‘Created: 02/28/02
‘Description: This script demonstrates how to use a constant to create a
‘standardized title bar message for pop-up dialogs displayed by the script
‘*************************************************************************
‘Specify the message to appear in each pop-up dialog title bar
Const cTitleBarMsg = “The Three Little Pigs”
‘Display the story
MsgBox “Once upon a time ”, vbOkOnly, cTitleBarMsg
MsgBox “There were 3 little pigs”, vbOkOnly, cTitleBarMsg
MsgBox “Who liked to build things.”, vbOkOnly, cTitleBarMsg
H I N T
Definition
A procedure is a collection of script
statements that are processed as a unit In Chapter 7, “Using Procedures
to Organize Scripts,” you will learn how to use procedures to improve the overall organization of your scripts and to create reusable units
of code.
Trang 7In this example, I wrote a small VBScript that tells a very brief story about three little pigs The script begins by defining a constant named cTitleBar I then used three MsgBox() state-ments to display the text that makes up the story The first argument in each MsgBox()statement
is a text message, which is then followed by a VBScript MsgBox()constant vbOkOnly This con-stant tells VBScript to only display the OK button on the pop-up dialog (a complete listing of
MsgBox()constants is available in Chapter 3, “VBScript Basics.” The last part of each MsgBox()
statement is the cTitleBarMsg constant VBScript automatically substitutes the value assigned to the cTitleBarMsgconstant whenever the script executes Figure 4.8 shows how the first pop-up dialog appears when the script is executed
I strongly recommend that you apply a naming convention for your constants that will uniquely identify them within your scripts A good naming convention will make your constants easy to locate and identify and will improve the over-all readability of your scripts For example, in this book I will use the following constant naming convention:
• Constant names begin with the lowercase letter c
• Constant names describe their contents using English words or easily identifiable parts of words
Other examples of tasks related to working with constants include assigning values such as numbers, strings, and dates For example, the following statement assigns a value of 1000to
a constant called cUpperLimit:
Const cUpperLimit = 1000
To define a text string, you must place the value being assigned within a pair of quotes, like this:
Const cMyName = “Jerry Lee Ford, Jr.”
H I N T
Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition
Figure 4.8
By referencing
the value
assigned to a
constant, you can
create a standard
title bar message
for every pop-up
dialog displayed
by your script
Trang 8In a similar fashion, you must use a pair of pound signs to store a date value within a con-stant, like this:
Const cMyBirthday = #11-20-64#
VBScript Run-Time Constants
VBScript supplies you with an abundance of built-in constants In Chapter 3 you learned about the constants associated with the MsgBox() function For example, the following VBScript statement executes the MsgBox()function using the vbOkOnlyconstant:
MsgBox “Welcome to my VBScript game!”, vbOkOnly
This statement displays a pop-up dialog that contains a single OK button In addition to these constants, VBScript supplies constants that help when you’re working with dates and times VBScript also supplies a number of constants that can help you manipulate the dis-play of text output and test the type of data stored within a variable
Using Date and Time Constants
Table 4.2 lists VBScript Date and Time constants
vbFirstFourDays 2 First full week with a minimum of 4 days in the new year
vbUseSystemDayOfWeek 0 Day of week as specified by the operating system
TA B L E 4 2 V B SC R I P T DA T E A N D TI M E CO N S T A N T S
Trang 9The following script demonstrates how the vbFridayconstant, listed in Table 4.2, can be used
to determine whether the end of the workweek is here:
‘*************************************************************************
‘Script Name: HappyHour.vbs
‘Author: Jerry Ford
‘Created: 10/26/02
‘Description: This script tells the user if it’s Friday
‘*************************************************************************
‘Perform script initialization activities
Dim TodaysDate
‘ Weekday is a VBScript function that gets the day of the week
TodaysDate = Weekday(Date)
If TodaysDate = vbFriday then MsgBox “Hurray, it is Friday Time “ & _
“to get ready for happy hour!”
You may have noticed the use of the &character in the previous example The &
character is a VBScript string concatenation operator It allows you to combine two pieces of text into a single piece of text
The first two lines of the script define a variable (we’ll discuss variables in detail in the next section) The third line assigns a numeric value to the variable In this case, the script used the VBScript Weekday()function to execute the VBScript Date()function The Date() func-tion retrieves the current date from the computer The Weekday()function then provides a numeric value to represent the weekday for the date Table 4.2 provides a list of the possible range of values in its Value column If the current day of the week is Friday, then the value returned by the Weekday()function will be 6 Because the vbFridayconstant has a value of 6, all that has to be done to determine if it is Friday is to compare the value returned by the
Weekday()function to the vbFriday If the two values are equal, a pop-up dialog displays the message “Hurray, it is Friday Time to get ready for happy hour!”
Using String Constants
Another group of constants that you may find useful are the VBScript string constants listed
in Table 4.3
T R I C K
Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition
Trang 10Using the constants shown in Table 4.3, you can control the manner in which output text is displayed For example, take a look at the following script:
‘*************************************************************************
‘Script Name: MsgFormatter.vbs
‘Author: Jerry Ford
‘Created: 02/28/02
‘Description: This script demonstrates how to use VBScript string constants
‘to control how text messages are displayed.
‘*************************************************************************
‘Specify the message to appear in each pop-up dialog title bar
Const cTitleBarMsg = “The three little pigs”
‘Specify variables used by the script
Dim StoryMsg
‘Specify the text of the message to be displayed
vbCrLf Chr(13) and Chr(10) Executes a carriage return and a line feed
vbNewLine Chr(13) and Chr(10) Adds a newline character
vbNullString String with no value Creates an empty string
TA B L E 4 3 V B SC R I P T ST R I N G CO N S T A N T S