Datasheet

Chapter 1: A Quick Introduction to Programming
12
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 state-
ments 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.
The script engine requires these beginning and ending statements, and if you omit them, the
script engine won’t understand your code and won’t allow your script to execute. Over the
course of this book you will encounter many different types of code blocks in VBScript.
To confuse matters, the term “block of code” is often used informally to describe any group of lines of
code. As a rule, “block of code” will refer to lines of code that work together to achieve a result.
Notice that the lines of code that are inside the block itself are indented by four spaces. This is an
extremely important concept but not for the reason you might think. This indenting has nothing
whatsoever to do with the script engine — it doesn’t care whether you add four spaces,
44 spaces, or none at all. This indenting is for the benefit of any humans who might be reading
your code. For example, the following script is completely legal and will execute just fine:
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
However, this code is very difficult to read. As a general rule of thumb, you indent code by four
spaces whenever a line or series of lines is subordinate to the lines above and below it. For ex-
ample, the lines after the
If clause and the Else clause belong inside the If...Else...End If
block, so you indent them to visually suggest the code’s logical structure. Presentation, while
having no bearing whatsoever on how the computer or script engine handles your code, is very
important when it comes to how humans read it. You should be able to look at the code and
get a sense for how it is organized and how it works. By seeing the indentations inside the
If...Else...End If block, you can not only read the code, but also “see” the branching logic
at that point in the code. Indenting is only one element of programming style, but learning and
following proper style and layout is essential for any programmer who wants to be taken
seriously.
The Else part of the block is optional. Sometimes you want to test for a certain condition, and
if that condition is
True , execute some code, but if it’s False , there’s no code to execute. For
example, you could add another
If...End If block to your script.
c01.indd 12c01.indd 12 8/27/07 7:45:21 PM8/27/07 7:45:21 PM