AL TE RI A Quick Introduction to Programming TE D MA A chapter covering the basics of VBScript is the best place to begin this book. This is because of the type of language VBScript is and the kind of users the authors see turning to it. In this chapter, you get a crash course in programming basics. You might not need this chapter because you’ve come to VBScript with programming skills from another language (Visual Basic, Visual Basic .
Chapter 1: A Quick Introduction to Programming ❑ Documenting code ❑ Advanced testing, debugging, and beta testing ❑ Rollout and support Think of this chapter as a brief introduction to the important building blocks of programming. It certainly won’t make you an expert programmer overnight, but it will hopefully give you the know-how you’ll need to get the most out of the rest of the book.
Chapter 1: A Quick Introduction to Programming It is not required that you declare all of the variables you use. By default, VBScript allows you to use undeclared variables. However, it’s strongly recommended that you get into the good habit of declaring all of the variables you use in your scripts. Declaring variables before use makes code easier to read and to debug later. Just do it! By declaring variables you also give them a name in the process. Here’s an example of a variable declaration in VBScript.
Chapter 1: A Quick Introduction to Programming All of the examples in this chapter are designed so that you can run them using the Windows Script Host (WSH). The WSH is a scripting host that allows you to run VBScript programs within Windows. WSH allows you to try out these example programs for yourself. You may already have WSH installed. To find out, type the previous example script into a text editor, save the file as TEST.VBS (it must have the .VBS extension, and not a .
Chapter 1: A Quick Introduction to Programming the YourName variable on the code line above. However, throughout this book you’ll often see the code commented in a similar way. This is because the point of the code is to instruct the reader in how a particular aspect of VBScript programming works, and the best way to do that is to add comments to the code directly. It removes ambiguity and keeps the code and comments together. Also worth noting is that comments don’t have to be on a separate line.
Chapter 1: A Quick Introduction to Programming Line 4 is another comment. Line 5 is more code. Now that you’ve initialized this variable, you’re going to do something useful with it. MsgBox is another built-in VBScript function that you will probably use a lot during the course of your VBScript programming. Using the MsgBox function is a good way to introduce the programming concept of passing function parameters, also known as arguments.
Chapter 1: A Quick Introduction to Programming ‘ First declare the variable Dim SomeVariable ‘ Initialize it with a value SomeVariable = “Hello, World!” MsgBox SomeVariable ‘ Change the value of the variable to something larger SomeVariable = “Let’s take up more memory than the previous text” MsgBox SomeVariable ‘ Change the value again SomeVariable = “Bye!” MsgBox SomeVariable Each time the script engine comes across a variable, the engine assigns it the smallest chunk of memory it needs.
Chapter 1: A Quick Introduction to Programming Here are the resulting message boxes generated by this code. The first is shown in Figure 1-3. Figure 1-3 The second message box is shown in Figure 1-4. Figure 1-4 The final message box is shown in Figure 1-5.
Chapter 1: A Quick Introduction to Programming You can store several different types of data in variables. These are called data types and so far you’ve seen two: ❑ String ❑ Integer You’ve also seen a single-precision floating-point number in the tax rate example. We’ll be covering all of them later on in the book. For now, just be aware that there are different data types and that they can be stored in variables.
Chapter 1: A Quick Introduction to Programming Dim YourName Dim Greeting YourName = InputBox(“Hello! What is your name?”) If YourName = “” Then Greeting = “OK. You don’t want to tell me your name.” Else Greeting = “Hello, “& YourName & “, great to meet you.” End If MsgBox Greeting Walking through the code, you do the following: 1.
Chapter 1: A Quick Introduction to Programming Figure 1-6 3. What happens if the user does (as you expect) type something into the input box? Well, this is where the next line comes in. Else You can actually begin to read the code and in fact doing this helps it to make sense.
Chapter 1: A Quick Introduction to Programming Before you move on to looping, you should know a few other things about If...Else...End If: ❑ The block of code containing the If...Else...End If is known as a block of code. A block is a section of code that has a beginning and an end, and it usually contains keywords or statements at both the beginning and the end. In the case of If...Else...End If, the If statement marks the beginning of the block, while the End If marks the end of the block.
Chapter 1: A Quick Introduction to Programming Dim YourName Dim Greeting YourName = InputBox(“Hello! What is your name?”) If YourName = “” Then Greeting = “OK. You don’t want to tell me your name.” Else Greeting = “Hello, “ & YourName & “, great to meet you.” End If If YourName = “Fred” Then Greeting = Greeting & “ Nice to see you Fred.” End If MsgBox Greeting ❑ The If...Else...End If block can be extended through the use of the ElseIf clause, and through nesting.
Chapter 1: A Quick Introduction to Programming Looping Branching allows you to tell the script to execute some lines of code, but not others. Looping, on the other hand, allows you to tell the script to execute some lines of code over and over again.
Chapter 1: A Quick Introduction to Programming Take a look at why the TryAgain = “No” line is essential to preventing an infinite loop. Going through the script line by line: 1. This first line starts the loop. Do This tells the script engine that you are starting a block of code that will define a loop. The script engine will expect to find a loop statement somewhere further down in the script. This is similar to the If...
Chapter 1: A Quick Introduction to Programming for their name again (wherein this time they will hopefully type something into the input box). If the user did type in his or her name, then you initialize your familiar Greeting variable. Note that in this case, you do not change the value of the TryAgain variable. This is because there is no need to loop around again because the user has entered a name. The value of TryAgain is already equal to “No”, so there’s no need to change it. 5.
Chapter 1: A Quick Introduction to Programming 1 to 10, and use the Counter variable to keep track of your counting. When you’ve gone through this loop ten times, stop looping and move on to the next bit of code.” Notice that every time the loop goes around (including the first time through), the Counter variable holds the value of the current count. The first time through, Counter equals 1, the second time through it equals 2, and so on up to 10.
Chapter 1: A Quick Introduction to Programming Figure 1-7 shows the final summary message generated by the code. Notice how well the information is integrated. Figure 1-7 Operators and Operator Precedence An operator acts on one or more operands when comparing, assigning, concatenating, calculating, and performing logical operations. Say you want to calculate the difference between two variables X and Y and save the result in variable Z.
Chapter 1: A Quick Introduction to Programming When you have a situation where more than one operation occurs in an expression, the operations are normally performed from left to right. However, there are several rules. Operators from the arithmetic group are evaluated first, then concatenation, comparison, and finally logical operators.
Chapter 1: A Quick Introduction to Programming Modularization, Black Boxes, Procedures, and Subprocedures Modularization is the process of organizing your code into modules, which you can also think of as building blocks. You can apply the principles of modularity to create your own personal set of programming building blocks, which you can then use to build programs that are more powerful, more reliable, easier to debug, and easier for you and your fellow programmers to maintain and reuse.
Chapter 1: A Quick Introduction to Programming Turning Code into a Function Some of the code that follows is from an example you used earlier in the chapter. Here’s how to turn code into a function. Function PromptUserName ‘ This Function prompts the user for his or her name. ‘ If the user enters nothing it returns a zero-length string. ‘ It incorporates various greetings depending on input by the user.
Chapter 1: A Quick Introduction to Programming Finally, notice how, in the second to last line, the function name PromptUserName is treated as if it were a variable. When you use functions (as opposed to subprocedures, which do not return a value), this is how you give the function its return value. In a sense, the function name itself is a variable within the procedure. Here is some code that uses the PromptUserName function.
Chapter 1: A Quick Introduction to Programming Else Greeting = “Hello, “ & YourName & “, great to meet you.” If YourName = “Fred” Then Greeting = Greeting & “ Nice to see you Fred.” End If End If MsgBox Greeting PromptUserName = YourName End Function As you can see, calling the PromptUserName function is pretty straightforward. Once you have written a procedure, calling it is no different than calling a built-in VBScript procedure.
Chapter 1: A Quick Introduction to Programming Understanding Top-Down Programming So far in this chapter you’ve written very simple top-down style programs. The process is simple to follow: ❑ Write some code. ❑ Save the code in a script file. ❑ Use Windows Script Host to execute the script. ❑ The Script Host starts executing at the first line and continues to the last line.
Chapter 1: A Quick Introduction to Programming When the user begins to do something, the program comes to life again. Suppose the user clicks a button. The program raises the Click event for the button that the user clicked. The code attached to that event starts to execute, performs some operations, and when it’s finished, the program returns to its wait state. As far as VBScript is concerned, the event-driven model is used heavily in scripting for the Web.
Chapter 1: A Quick Introduction to Programming Figure 1-8 Expect the Unexpected Always remember that anything that can happen probably will happen. The idea here is to code defensively — preparing for the unexpected. You don’t need to become totally fixated on preparing for all contingencies and remote possibilities, but you can’t ignore them either. You especially have to worry about the unexpected when receiving input from the user, from a database, or from a file.
Chapter 1: A Quick Introduction to Programming Always Favor the Explicit over the Implicit When you are writing code, constantly ask yourself: Is my intent clear to someone reading this code? Does the code speak for itself? Is there anything mysterious here? Are there any hidden meanings? Are the variable names too similar to be confusing? Even though something is obvious in your mind at the moment you are typing the code, it doesn’t mean it will be obvious to you six months or a year from now — or to some
Chapter 1: A Quick Introduction to Programming ❑ Are you writing a block of code that you think you might need again in some other part of the script, or in another script? Move it to its own procedure. ❑ Are you writing some code that you think someone else might find useful? Move it. This isn’t a science and there are no hard and fast rules for code — after all, only you know what you want it to do. Only you know if parts are going to be reused later. Only you know how complex something will turn out.
Chapter 1: A Quick Introduction to Programming Use Comments to Make Your Code More Clear and Readable, but Don’t Overuse Them When writing code, strive to make it as self-documenting as possible. You can do this by following the guidelines set out earlier. However, self-documenting code is hard to achieve and no one is capable of 100% self-documenting code. Everyone writes code that can benefit from a few little scribbles to serve as reminders in the margins.