Microsoft WSH and VBScript Programming for the Absolute Beginner Part 14 pps

10 328 0
Microsoft WSH and VBScript Programming for the Absolute Beginner Part 14 pps

Đang tải... (xem toàn văn)

Thông tin tài liệu

110 Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition StoryMsg = “Once upon a time there were 3 little pigs” & vbCrLf & _ “who liked to build things.” & vbCrLf & vbCrLf & _ vbTab & “The End” ‘Display the story to the user MsgBox StoryMsg, vbOkOnly + vbExclamation, cTitleBarMsg The text message that is displayed by the script is Once upon a time there were 3 little pigs who liked to build things. The End Notice how the vbCrLf and vbTab constants have been placed throughout the text to specify how VBScript should display message text. Figure 4.9 shows the output that is displayed when this script is executed. If the vbCrLf and vbTab constants were removed from the formatted message, the text dis- played in the pop-up dialog would look completely different, as shown in Figure 4.10. Figure 4.9 Using VBScript string constants to manipulate the display of text in pop-up dialogs. Figure 4.10 Displaying the same output as the previous example without the use of the vbCrLf and vbTab constants. For more information about VBScript constants, go to http://www.msdn.microsoft.com and click on the VBScript Documentation link. Storing Data That Changes During Script Execution Chances are most programs that you write will have data in them that will need to be mod- ified. For example, you may write a script that asks the user for input and then modifies the data while processing it. In this situation, you can define variables. Two categories of variables are available to your scripts: variables that you define within your scripts and environment variables that are maintained by Windows that your scripts can refer- ence. I’ll demonstrate how to work with both categories of variables in the sections that follow. VBScript Data Types Unlike many other programming languages, VBScript only supports one type of variable, called a variant. However, a variant is very flexible and can be used to store a number of different types of data. Table 4.4 lists variant data types supported by VBScript. 111 Chapter 4 • Constants, Variables, and Arrays Definition A variant is a type of variable that can contain any number of different types of data. Subtype Description Boolean A variant with a value of True or False Byte An integer whose value is between 0 and 255 Currency A currency value between –922,337,203,685,477.5808 and 922,337,203,685,477.5807 Date A number representing a date between January 1, 100 and December 31, 9999 Double A floating-point number with a range of –1.79769313486232E308 and –4.94065645841247E-324 or 4.94065645841247E-324 and 1.79769313486232E308 Empty A variant that has not been initialized Error A VBScript error number Integer An integer with a value that is between –32,768 and 32,767 Long An integer whose value is between –2,147,483,648 and 2,147,483,647 Null A variant set equal to a null value Object An object Single A floating-point number whose value is between –3.402823E38 and –1.401298E-45 or 1.401298E-45 and 3.402823E38 String A string up to two billion characters long TABLE 4.4 VBSCRIPT SUPPORTED VARIANT S UBTYPES 112 Variants automatically recognize the types of data that are assigned to them and act accord- ingly. In other words, if a date value is assigned to a variant, then your script can use any of VBScript’s built-in date functions to work with it. Likewise, if a text string is assigned to a variant, then your script can use any of VBScript’s built-in string functions to work with it. Like constants, VBScript provides you with some control over the way in which it identifies the types of values stored in a variant. For example, if you assign 100 as the variable value, then VBScript automatically interprets this value as a number. But if you enclose the value in quotation marks, VBScript treats it like a string. VBScript also provides the capability to convert data from one type to another using built-in VBScript func- tions. You can use these functions within your scripts to change the way VBScript views and works with data. For example, the following VBScript statement defines a variable named MyBirthday and assigns it a text string of “November 20, 1964”: MyBirthday = “November 20, 1964” VBScript views this variable’s value as a text string. However, using the Cdate() function, you can covert the string value to date format: MyBirthday = CDate(MyBirthday) Now, instead of seeing the variable’s value as “November 20, 1964”, VBScript sees it as 11/20/1964. VBScript provides a large number of conversion functions that you can use to convert from one data type to another. These functions include Asc(), Cbool(), Cbyte(), Cbur(), Cdate(), CDbl(), Chr(), Cint(), CLng(), CSng(), and CStr(). For more information about how to use these functions, see Chapter 7. Defining Variables VBScript provides two ways of defining variables: dynamically, and formally, using the Dim statement. To dynamically create a variable within a script, you simply need to reference it like this: MyBirthday = #November 20, 1964# HINT Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition Definition The term string and text string are used synonymously throughout this book to refer to text-based data or other types of data that have been enclosed within a pair of quotations. Using this method of programming, you can define variables anywhere within your script. However, I strongly recommend against creating variables in this manner. It is much better to formally define any variables used in a script all at once at the beginning of the script. This helps keep things organized and easier to read. In addition, I also strongly suggest that you use the Dim statement. The syntax of the Dim statement is as follows: Dim VariableName VariableName is the name of the variable being defined. For example, the following state- ment defines a variable named MyBirthday: Dim MyBirthday After a variable has been defined, you can assign a value to it, like this: MyBirthday = #November 20, 1964# Always use the Dim statement to make your code more readable and to explicitly show your intentions. You can define multiple variables within your scripts using multiple Dim statements: Dim MyBirthday Dim MyName Dim MyAge However, to reduce the number of lines of code in your scripts, you have the option of defin- ing more than one variable at a time using a single Dim statement, by separating each vari- able with a comma and a space: Dim MyBirthday, MyName, MyAge As I already stated, it’s better to formally define a variable before using it. One way to make sure that you follow this simple rule is to place the Option Explicit statement at the begin- ning of your scripts. The Option Explicit statement generates an error during script execution if you attempt to reference a variable without first defining it. Therefore, Option Explicit helps remind you to follow good programming practices when working with variables. To test the use of the Option Explicit statement, let’s take a look at another example: ‘************************************************************************* ‘Script Name: BigBadWolf.vbs ‘Author: Jerry Ford ‘Created: 02/29/02 ‘Description: This script demonstrates how to use the Option Explicit ‘statement ‘************************************************************************* 113 Chapter 4 • Constants, Variables, and Arrays 114 Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition ‘For the explicit declaration of all variables used in this script Option Explicit ‘Create a variable to store the name of the wolf Dim WolfName ‘Assign the wolf’s name to the variable WolfName = “Mr. Wiggles” ‘Display the story MsgBox “Once upon a time there was a big bad wolf named “ & WolfName & _ “ who liked to eat little pigs”, vbOkOnly In this example, the Option Explicit statement is the first statement in the script. By mak- ing it the first statement in the script, Option Explicit will affect all variables that follow. The next statement defines a variable representing the name of the wolf. The statement after that assigns a name to the variable, which is then used by the script’s final statement to tell the story. Run the script and you’ll see that everything works fine. Then modify the script by placing a comment in front of the Dim statement and run the script again. This time, instead of executing properly, the error shown in Figure 4.11 will appear, indicating that the script attempted to reference an undefined variable. Figure 4.11 Use the Option Explicit statement in all your scripts to prevent the use of undefined variables. To summarize, the following list provides the guidelines that you should follow when work- ing with variables: • Define your variables at the beginning of your scripts in one location. • Use the Option Explicit statement to enforce formal variable declaration. • Use the Dim statement to define each variable. Up to this point in the chapter, I have not been following these rules because I had not got- ten to them yet. However, from this point on, you’ll find them applied consistently in every script that uses variables. There is one exception to the set of rules that I want to point out. In certain cases, you can limit the availability of a variable and its value to a specific portion of your scripts. This is called creating a local variable and can be useful when manipulating a sensitive variable to make sure that its value is not accidentally modified by other parts of the script. I’ll provide more information about local variables a little later in this chapter. Variable Naming Rules Another important issue that merits attention is the proper naming of variables. VBScript has a number of rules that you must follow to avoid errors from inappropriately named vari- ables. These rules include • Variable names must be less than 256 characters long. • Variable names must begin with an alphabetic character. • Only letters, numbers, and the _ character can be used when creating variable names. • Reserved words cannot be used as variable names. • Variable names cannot contain spaces. • Variable names must be unique. One more important thing to know about VBScript variables is that they are case-insensitive. This means that capitalization does not affect VBScript’s capability to recognize a variable. Therefore, if a script defines a variable as Dim MyBirthday and then later references it as MYBIRTHDAY, VBScript recognizes both spellings of the variable name as the same. However, mixing cases in this manner can be confusing and you should do your best to use a consis- tent case throughout your scripts. TRICK 115 Chapter 4 • Constants, Variables, and Arrays 116 Variable Scope Another key concept that you need to understand when working with variables is variable scope. In this context, scope refers to the ability to reference a variable and its assigned value from various locations within a script. Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition In the Real World You should assign descriptive variable names in your scripts to make them easier to identify and understand. Select a standard approach in the way that you use case in the spelling of your variables. Up to this point in the book, I have defined variables using complete words or parts of words, and I began each word or part of a word with a capital letter, as in Dim MyBirthday. Another approach that many programmers take when naming variables is to add a three- character prefix, sometimes referred to as Hungarian Notation, to the beginning of each vari- able name to identify the type of data stored in the variable. For example, instead of naming a variable Mybirthday, you would name it dtmMyBirthday. This way by examining the first three characters of the variable name, you’ll be able to tell that it contains a date. The following list identifies typical prefixes associated with each of the variable subtypes supported by VBScript. • Boolean — bln • Byte — byt • Currency — cur • Date — dtm • Double — dbl • Error — err • Integer — int • Long — lng • Object — obj • Single — sng • String — str • Variant — var Now that I have formally introduced you to Hungarian Notation, I’ll begin using it when naming variables in all the script examples you’ll see throughout the rest of this book. VBScript supports two different variable scopes, global and local. A variable with a global scope can be accessed from any location within the script. However, a variable with a local scope can only be referenced from within the procedure that defines it. VBScript supports two types of procedures, subroutines and functions, both of which are discussed in detail in Chapter 7. As you know, a procedure is a collection or group of statements that is executed as a unit. Without getting too far ahead of myself, for now just note that a variable defined outside a procedure is global in scope, meaning that it can be accessed from any location within the script, including from within the script’s procedures. A variable that is local in scope is defined within a procedure. Modifying Variable Values with Expressions Throughout this chapter, you have seen the equals sign (=) used to assign value to variables, like this: strMyName = “Jerry Lee Ford, Jr.” To change the value assigned to a variable, all you have to do is use the equals sign again, along with a new value, like this: strMyName = “Jerry L. Ford, Jr.” The two previous examples set and then modified the value assigned to a text variable. How- ever, this same approach works just as well for other types of variables, such as those that contain numeric values: Option Explicit Dim intMyAge intMyAge = 37 intMyAge = 38 In this example, the variable is defined and then assigned a numeric value. The value assigned to that variable is then modified to a different number. VBScript provides addi- tional ways of modifying the value of numeric variables using the equals sign and VBScript arithmetic operators. Table 4.5 lists the VBScript arithmetic operators. 117 Chapter 4 • Constants, Variables, and Arrays 118 The best way to explain how these arithmetic operators are used is to show you an example. Take a look at the following script: ‘************************************************************************* ‘Script Name: MathDemo.vbs ‘Author: Jerry Ford ‘Created: 02/29/02 ‘Description: This script demonstrates how to use various VBScript ‘arithmetic operators ‘************************************************************************* ‘Force the explicit declaration of all variables used in this script Option Explicit ‘Create a variable to store the name of the wolf Dim intMyAge ‘Assign my initial starting age Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition Operator Description + Addition - Subtraction * Multiplication / Division - Negation ^ Exponentiation \ Integer division Mod Modulus TABLE 4.5 VBSCRIPT ARITHMETIC O PERATORS intMyAge = 37 WScript.Echo “I am “ & intMyAge ‘Next year I will be intMyAge = intMyAge + 1 WScript.Echo “Next year I will be “ & intMyAge ‘But I am not that old yet intMyAge = intMyAge - 1 WScript.Echo “But I still am “ & intMyAge ‘This is how old I’d be if I were twice as old as I am today intMyAge = intMyAge * 2 WScript.Echo “This is twice my age “ & intMyAge ‘And if I took that value, divided it by 5, added 3, and multiplied it ‘by 10 intMyAge = intMyAge / 5 + 3 * 10 WScript.Echo “This says that I will be “ & intMyAge If you run this script, you’ll see the results shown in Figure 4.12. 119 Chapter 4 • Constants, Variables, and Arrays Figure 4.12 Using VBScript arithmetic operators to modify numeric variables. . ‘statement ‘************************************************************************* 113 Chapter 4 • Constants, Variables, and Arrays 114 Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition For the explicit declaration of all variables used. this: MyBirthday = #November 20, 1964# HINT Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition Definition The term string and text string are used synonymously throughout this. to reference a variable and its assigned value from various locations within a script. Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition In the Real World You should

Ngày đăng: 03/07/2014, 18:20

Từ khóa liên quan

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan