Plus (+) Operator

VBScript allows you to use the plus (+) operator to concatenate strings. However, this usage of plus (+) operator should be avoided. This is because the plus (+) operator, when used to concatenate strings, can cause unwanted implicit type coercion. Try this code:

Dim strFirst
Dim lngSecond
strFirst = CStr(50)
lngSecond = CLng(100)
MsgBox strFirst + lngSecond

The resulting dialogue box will display the number 150, which means that it added the two numbers mathematically rather than concatenating them. Now, this is admittedly a very silly example, but it illustrates that the plus (+) operator has different effects when you are not using it in a strictly mathematical context. The plus (+) operator uses the following rules when deciding what to do.

If both variables have the String subtype, the VBScript will concatenate the.
If both variables have any of the numeric subtype, then VBScript will add them.
If one of the variable has a numeric subtype, and the other has the String subtype, then VBScript will attempt to add them. If the variable with the String subtype does not contain a number, then a "Type Mismatch" error will occur.

Your best bet is to not worry about these rules and remember only the following:

Use the plus (+) operator only when you explicitly want to perform math on numeric values.
Always use the & operator to concatenate strings.
Never use the plus (+) operator to concatenate strings.

First

Another Coercion Example

Run the following code in Windows Script Host:

Dim intTest
intTest = CInt(100)
MsgBox "TypeName after initialization to 100: " & _
TypeName(intTest)
intTest = intTest + 1000000
MsgBox "TypeName after adding 1,000,000: " & _
TypeName(intTest)
intTest = intTest + 10000000000
MsgBox "TypeName after adding another 10,000,000,000: " & _
TypeName(intTest)

Notice that we initialized the variable with a value of 100, and use the CInt ( ) function to coerce the subtype into Integer. The first call to the TypeName ( ) function reflects String. Then we added 1,000,000 to the variable. The next call to the TypeName ( ) function reveals that VBScript coerced the subtype to Long. Why did it do this? Because we exceeded the upper limit of the Integer subtype, which is 32,767. VBScript will promote numeric subtype when the value exceeds the upper or lower limits of the current numeric subtype. Finally, we add another ten billion to the variable. This exceeds the upper limit of the Long subtype, so VBScript upgrades the subtype to Double.

First
Next

Long Coerced into String

Dim lngTest
lngTest = CLng(100)
MsgBox "Type after initialization: " & TypeName(lngTest)
lngTest = lngTest + 1000
MsgBox "TypeName after adding 1000: " & TypeName(lngTest)
lngTest = lngTest * 50
MsgBox "TypeName after multiplying the 50: " & TypeName(lngTest)
lngTest = "Hello"
MsgBox "TypeName after assigning value of 'Hello': " & TypeName(lngTest)

If you run this code using Windows Script Host, you'll see that the first three calls to the TypeName ( ) function reveal that the subtype is Long. Then, after we changed the value of the variable to "Hello", the subtype is automatically coerced into String. What this code illustrates is that, once the subtype is established as Long, it stays Long as long as we keep changing the value to other numbers. VBScript has no reason to change it, because the values we put in it remain in the range of the Long subtype. However, when we place text in the variable, VBScript sees that the new value is not appropriate for the Long subtype, so it changes it to String.

First
Next

Subtype Change

Din lngAge
lngAge = InputBox("Plese enter your age in years")
MsgBox "TypeName After InputBox: " & TypeName(lngAge)
If IsNumeric(lngAge) Then
lngAge = lngAge + 50
MsgBox "TypeName after Adding 50: " &TypeName(lngAge)
MsgBox "In 50 years you will be " & lngAge & "years old."
Else
MsgBox "Sorry, but you did not enter a valid number."
End If

While you have to aware of implicit type coercion, there is no reason to fear it. VBScript is not going to arbitrarily go around changing subtypes on you. Implicit type coercion only happens when you assign a new value to a variable that does not fit the current subtype. Generally, once a Variant variable has a subtype (based on the value first placed within it, or based on a subtype that your code explicitly coerced), it will keep that subtype as you place new value in the variable.

Where do you need to watch out for implicit type coercion is when you are dealing with a mixture of data types. I saw this in the example: when the data comes back from the InputBox ( ) function, it was a string. Then we did soem math on it, which turned it into a number. Give this code a try:

Dim lngTest
lngTest = CLng(100)
MsgBox "Type after initialization: " & TypeName(lngTest)
lngTest = lngTest + 1000
MsgBox "TypeName after adding 1000: " & TypeName(lngTest)
lngTest = lngTest * 50
MsgBox "TypeName after multiplying the 50: " & TypeName(lngTest)
lngTest = "Hello"
MsgBox "TypeName after assigning value of 'Hello': " & TypeName(lngTest)

First
Next

Double Subtype - TWO

Din lngAge
lngAge = InputBox("Plese enter your age in years")
MsgBox "TypeName After InputBox: " & TypeName(lngAge)
If IsNumeric(lngAge) Then
lngAge = lngAge + 50
MsgBox "TypeName after Adding 50: " &TypeName(lngAge)
MsgBox "In 50 years you will be " & lngAge & "years old."
Else
MsgBox "Sorry, but you did not enter a valid number."
End If

In the example above, VBScript automatically knew that we wnated the value the variable to be a number because our code added 50 to the variable. VBScript says, "Oh, we're doing math. I better change the subtype to a numeric one before I do the math, because I can't do math on Strings." This is pretty straightforward. What isn't so straightforward is that it chose the Double subtype instead of Long or Integer or Bytes.

We may never know the exact reason why VBScript chooses a Double in this situation, but it is probably a prevention measure. Other than the Decimal subtype, which is rarely used and only then for extremely large or extremely small number, the Double subtype is the most capable of holding large numbers. Rather than go to the trouble of figuring out the result of the math first, and then deciding on a subtype, VBScript just picks the most accommodating subtype, Double, so that it can be reasonably sure that the result of the math will fit in the variable. In other words, VBScript makes the safest choice.

First
Next

Double Subtype - ONE

Din lngAge
lngAge = InputBox("Plese enter your age in years")
MsgBox "TypeName After InputBox: " & TypeName(lngAge)
If IsNumeric(lngAge) Then
lngAge = lngAge + 50
MsgBox "TypeName after Adding 50: " &TypeName(lngAge)
MsgBox "In 50 years you will be " & lngAge & "years old."
Else
MsgBox "Sorry, but you did not enter a valid number."
End If

However, does it really matter that VBScript coerced the variable into Double instead of a Long? There are both numeric subtypes, and the math has exactly the same result. Why care? Well, it's not the end of the world, except that the Double subtype theoretically takes a little bit more processing power than the Long, because the Double is a floating point, numeric subtype (floating point numbers require a greater degree of accuracy, and therefore the processor has to work a little harder to ensure that accuracy). If you were explicitly coercing the subtype, as in the code I started with, you might not choose the Double, because the Double is generally only used for very large or small numbers. You might choose Integer, or Long, or even Byte. That said, sometimes you need to care what the subtype is because you are planning to pass the variable to a method of a COM object that expects an explicit subtype.

The point of this little exercise is not to debate one numeric subtype is better than another, rather to illustrate implicit type coercion. VBScript automatically knew that we wanted the value the variable to be a number.

First
Next

Second Call TypeName ( ) Function

Din lngAge
lngAge = InputBox("Plese enter your age in years")
MsgBox "TypeName After InputBox: " & TypeName(lngAge)
If IsNumeric(lngAge) Then
lngAge = lngAge + 50
MsgBox "TypeName after Adding 50: " &TypeName(lngAge)
MsgBox "In 50 years you will be " & lngAge & "years old."
Else
MsgBox "Sorry, but you did not enter a valid number."
End If

The second call to the TypeName ( ) function comes after we add 50 to it, and shows that the subtype is Double. Wait a minute - Double? Why Double? Why not once of the whole number subtypes, such as Integer or Long? I didn't introduce any decimal places in this math? Why would VBScript implicitly coerce the subtype into Double? The answer is because VBScript determined that this was the best thing to do. Since we did not use a conversion function to explicitly tell VBScript to change the variable to one subtype or another, it evaluated the situation and chose the subtype that it thought was best. You have to be careful, because it can be tricky to predict exactly which subtype VBScript will choose.


First
Next

First Call TypeName ( ) Function

Din lngAge
lngAge = InputBox("Plese enter your age in years")
MsgBox "TypeName After InputBox: " & TypeName(lngAge)
If IsNumeric(lngAge) Then
lngAge = lngAge + 50
MsgBox "TypeName after Adding 50: " &TypeName(lngAge)
MsgBox "In 50 years you will be " & lngAge & "years old."
Else
MsgBox "Sorry, but you did not enter a valid number."
End If

The first call to the TypeName ( ) function shows that the subtype is String. That is because data coming back form the InputBox function is always treated as String data, even when the user types in a number. Remember that the String subtype can hold just about any kind of data. However, when number and dates and Boolean True/False values are stored in a variable with the String subtype, they are not treated simple as strings of text with no special meaning. This is why, when our code tries to do math on the String value, VBScript must first coere the subtype to a numeric one.

First
Next

Implicit Type Coercion

Implicit type coercion is when a Variant variable changes its subtype automatically. Sometimes, this can work in your favor, and sometimes it can present a problem.

He is a code that asks the user for his age:

Dim lngAge
lngAge = InputBox("Plese enter your age in years")
If IsNumeric(ingAge) Then
lngAge = CLng(lngAge)
lngAge = lngAge + 50
MsgBox "In 50 years, you will be " & CStr(lngAge) & " years Old."
Else
MsgBox "Sorry, but you did not enter a valid number."
End If

Notice how we use the CLng ( ) and CStr ( ) functions to explicitly coerce the subtype. Well, in the case of this particular code, these functions are ot strictly necessary. The reason is that VBScript's inplicit type coercion would have done approximately the same thing for us. Here is the code again, without the conversion functions.

Dim lngAge
lngAge = InputBox("Plese enter your age in years")
If IsNumeric(ingAge) Then
lngAge = lngAge + 50
MsgBox "In 50 years, you will be " & lngAge & " years Old."
Else
MsgBox "Sorry, but you did not enter a valid number."
End If

Because of implicit type coercion, this code works the same way as the original code. Take a look at the fifth line. We did not explicitly coerce the subtype to Long, but the math still works as you would expect. Let us run the same code, but with some TypeName ( ) functions thrown in so that we can watch the subtypes change.

Next

Is Functions - IsDate

Dim datBirth
datBirth = InputBox("Please enter the date on which you were born")
If IsDate(datBirth) Then
datBirth = CDate(datBirth)
MsgBox "You were born on day " & Day(datBirth) & _
" of month "& Month (datBirth) & " in the year " & _
year(datBirth) & "."
Else
MsgBox "Sorry, but you did not enter a valid date."
End If

Day ( ), Month ( ), and year ( ) are built-in VBScript functions that you can use to return the different parts of a date. Not however, that not all of the "Is" functions work strictly on the values, as IsNumeric ( ) and IsDate ( ) do. The function IsEmpty ( ), IsNull ( ), and IsObject ( ) examine the subtype of the variable, not the value.

First

Is Functions - IsNumeric

You can often get around Type Mismatch errors by using Is Functions. For example here is a code that asks the user his age. Since we don't have any control over what the user types in, we need to varify that he actually typed in a number:

Dim lngAge
lngAge = InputBox("Please enter your age in years")
If IsNumeric(lngAge) Then
lngAge = CLng(lngAge)
lngAge = lngAge + 50
MsgBox "In 50 years, you will be " & CStr(lngAge) & " years old."
Else
MsgBox "Sorry, but you did not enter a valid number."
End If

Notice how we use the IsNumeric ( ) function to test whether or not the user actually entered a valid number. Since we're palnning to use the CLng ( ) function to coerce the subtype, we want to avoid a Type Mismatch error. What we have not stated explicitly is that the subtype of the variable does not have to be numeric in order for IsNumeric ( ) to return true. IsNumeric ( ) examines the actual value of the variable, rather than its subtype. The subtype of the variable and the value of the variable are two different things. The behavior is actually what allows us to use IsNumeric ( ) to avoid a Type Mismatch error. If IsNumeric ( ) examined the subtype, it would not work as we have been using it. In line three of the above example, the subtype of the lngAge variable is String, yet IsNumeric ( ) returns True if the variable has a number in it. That is because IsNumeric ( ) is considering the value of lngAge, not the subtype. We can test the value before trying to convert the variable's subtype to a different subtype. The function IsDate ( ) works in exactly the same way.

First
Next

Runtime Error - Type Mismatch

Often you are not exactly sure what type of data a variable might hold initially, and you need to be sure of what type of data it is before you try to use a conversion function on it. This is because using a conversion function on the wrong type of data can cause a runtime error. For example, try this code:

Dim varTest
varTest = "Hello"
varTest = CLng(varTest)

This code will cause a runtime error on line 3: "Type Mismatch". Not a nice thing to happen when your code is trying to accomplish something. Obviously, this little code sample is pretty silly, because we knew that the variable contained a String when we tried to convert it to a Long. This is especially true when you are (1) accepting input from a user (2) reading data from a database (3) reading data from a file.

First
Next

Forcing Date/Time

There are different ways that we can force the subtype to be Date instead of String:

Dim varTest
varTest = #5/16/99 12:30 PM#
MsgBox TypeName(varTest)

This example surrounds the date/time value in # signs instead of quotes. This is the VBScript way of identifying a date literal (VB/VBA uses this convention as well). A literal is any value that is expressed directly in your code, as opposed of being expressed via a variable or named constant. The number 12 and the string "Hello There" that I used in previous examples are also literals. By enclosing the date/time in # signs rather than quotes, we are telling VBScript to treat the value as a date, not as a string. As a result when the date literal gets stored in the variant variable, the subtype comes out as Date.

Here is another example to force date/time instead of String.

Dim varTest
varTest = CDate("5/16/99 12:30 PM")
MsgBox TypeName(varTest)

This example uses the CDate ( ) conversion function to achieve the same thing. Once again, the first version is theoretically faster since it does not require an extra function.

First
Next

Using Date/Time Values

Let us look at a similar example, this time using date/time values.

Dim varTest
varTest = "5/16/99 12:30 PM"
MsgBox TypeName(varTest)

When we run this code in Windows Script Host, the variable assignment results in a subtype of String, although you might expect it to be Date. We get the String subtype because we put the date/time value in quotes. We saw this principle in action in another post when we put the number 12 in quotes in the variable assignment.

First
Next

Coercing Variable for Integer Subtype

Dim varTest
varTest = 12
MsgBox TypeName(varTest)

Dim varTest
varTest = CInt("12")
MsgBox TypeName(varTest)

Dim varTest
varTest = "12"
varTest = CInt(varTest)
MsgBox TypeName(varTest)

All three of these examples achieve the same thing: coercing the varTest variable to have the Integer subtype. The first example results in the Integer subtype because we did not enclose the value 12 in quotes. This tells VBScript that we want the number to be treated as a number, not as text. The second example uses the CInt ( ) conversion function to transform the string value "12" into an Integer value before placing it in the variable. This tells the VBScript that we want the subtype to be Integer right from the start. The third example does the conversion after the fact. Any of these is a valid way to make sure that the value we are placing in the variable is treated as a numeric Integer value. However, the first example might be better because it is theoretically faster because we're not making the extra call to the CInt ( ).

Note that this code would be redundant:

Din varTest
varTest = CInt(12)

Because we don not have quotes around the 12, its subtype will automatically be Integer. However, this code has a different effect:

Din varTest
varTest = CLng(12)

This tells vbscript to make sure that the subtype of the variable is Long. The same numeric value of 12 is stored in the variable, but instead of being classified as an Integer, it is classified as a Long. This would be significant if you were passing the value to a VB/COM function that requires a Long.

First
Next

Dealing With String Values

Dealing with script values such as "Hello There" is generally straightforward - unless your string value looks like a number, as in the following example.

Dim varTest
varTest = "12"
MsgBox TypeName(varTest)

Question is that why does the TypeName ( ) function returns "String" when we clearly passed it a numeric value of 12? This is because we placed value 12 in quotes. By placing it in quotes, we told VBScript that we mean for the value to be treated as a number:

Dim varTest
varTest = 12
MsgBox TypeName(varTest)

Dim varTest
varTest = CInt("12")
MsgBox TypeName(varTest)

Dim varTest
varTest = "12"
varTest = CInt(varTest)
MsgBox TypeName(varTest)

All three of these examples given above give the same result.

First
Next

Data Type Prefix

Therefore, a data type prefix can tell you the programmer (and the other programmers who are reading or modifying your code) what type of data you intend for a variable to hold. In other words, Variant variables can hold any kind of data, but in practice, any given variable should generally only hold one kind of data. This is not an absolute, as there are certainly legitimate circumstances under which you would intend for a variable to be able to hold multiple data types. By placing a placing a data type prefix in front of your variable name, you make it obviously clear what type of data you intend for that variable to hold, even if you intend for it to, or expect that it night need to, hold multiple types of data. Here is a short list of data type prefixes that are commonly used.

var - Variant
str - String
int - Integer
lng - Long
byt - Byte
sng - Single
dbl - Double
cur - Currency
obj - Object
bool - Boolean

The variable prefix is best used when you don't know exactly what type of data might end up in a variable, or when you intend for that variable to hold all kinds of data.

First
Next

Data Type Prefix - Hungarian Notation

Dim varTest
varTest = "Hello There"
MsgBox TypeName(varTest)

You may have noticed that I named the variable in the above example varTest. This might look strange if you have not seen "Hungarian Notation" before. Hungarian Notation defines the practice of placing prefixes in front of variable names in order to convey the data type of the variable, as well as its "scope". It might seem unnecessary to include a data type prefix since VBScript only supports one data type, the Variant. However, data type prefixes for Variant Variables are just as useful and important, or even more so, as they are for languages that support specific data types. This is because Variant Variables can hold virtually any kind of data.

First
Next

Placing New Value

A Variant variable automatically chooses its subtype whenever you place a new value into it. It does this by examining the value placed into and making its best guess as to what the appropriate subtype is. Sometimes, though, the Variant’s “best guess” is not quite what you expect. However, you can control this by being careful and explicit in your code. Let’s look at some code example that will demonstrate the principles that I have been talking about here.

Dim varTest
varTest = "Hello There"
MsgBox TypeName(varTest)

This makes sense. I placed a text (a.k.a. "string") value into the variable varTest, and VBScript appropriately decided that the variable should have the String subtype.

First
Next

Testing For and Coercing Subtypes

There are two built-in VBScript functions that allow you to check what the subtype is for Variant variable. These functions are VerType ( ) and TypeName ( ). These two functions do pretty much the same thing, but VarType ( ) returns a numeric representation of the subtype and TypeName ( ) returns a string representation.

VBScript also provides some functions that you can use to force (or ‘coerce’) the Variant to have a specific subtype. These conversion functions are especially useful when you need to pass data of a certain data type to a VB/COM object that expects data of a specific data type. This is also useful when you want to ensure that the value stored in a Variant variable is treated in a certain way. For example, the value 12 can be stored in a Variant variable with either a String subtype or one of the numeric subtypes. If you want to make sure that the number 12 is treated as a number, and not a string, you can use the CLng ( ) conversion function to make sure that the subtype is Long and not String.

First
Next

Another Downside of the Variant

Another downside of Variant variables is that you as a programmer must sometimes pay close attention to what the Variant subtype is at any given moment. This is because of something called implicit type coercion, which is what happens when a variant variable changes its subtype automatically. Implicit type coercion occurs when you assign a new value to a Variant variable that is different then the value currently stored within it. The Variant variable “coerces” the subtype into another subtype based on the type of data assigned to it.

First
Next

Downside of the Variant

The flexibility comes at a price, however. One downside of the Variant is that takes up more memory than many of the specific Visual Basic data types. For this reason, Visual Basic developers will normally only choose to declare a variable as a Variant when they specifically what that variable to be able to handle more than one data type. After all, why take up more memory than you have to?

First
Next

VBScript: The Variant

As I said in another post, the Variant is the only data type supported in VBScript. Programmers in another language who are accustomed to using a language that offers a wide range of data types might find this disconcerting. However, the good news is that the Variant is also very flexible. Because of the Variant’s ability to store many different data types, your script can handle just about any kind of data you need: numbers, strings (text), and dates, plus other more complex data types such as objects and arrays.

Next

Late Bound and Early Bound

Note that the Object data type is generic and can hold a reference to any kind of object. Object references stored in a variable of the Object data type are said to be late bound, meaning that object’s interface cannot be solved until runtime. Variables and routine parameters can also be declared as a specific object type. Variables of this sort are said to be early bound, meaning that the interface of the object was known at compile time. A late-bound Variant object variable can be passed to a VBScript procedure that uses an early bound parameter. That said, I am not going to be discussing objects in this post.

Also if you are also familiar with the Visual Basic data types, you may have noticed that I did not include the “fixed length” String data type in our list. This is because fixed length string cannot be stored in a Variant, and I am primarily interested in the data types that can be used as Variant subtypes.

First

Importance of Data Type

The data type is also important for another reason: certain types of operations can only be performed on certain data types. For example, before you can perform addition, subtraction, or multiplication on a variable, it must be a numeric data type. This allows the compiler and runtime engine to treat the variable as a number and perform mathematical operations on it. By declaring a variable with one of the numeric data types, you ensure that only numbers will be stored in it, and you can perform mathematical operations on that variable without having to worry about whether the variable actually has a numerical value.

First
Next

Memory and Data Type

A visual Basic variable declared with one of the numeric data types would take up one, two, or four bytes of memory, depending on whether it has the Byte, Integer, or Long data type, respectively. A long variable with a value of 1 takes up the exact same four bytes of memory that a Long variable with a value of 2,000,000 does. What’s difference is the range of numeric values that each of the numeric types can support. Because a Long variable takes up more memory than an Integer variable, larger (and smaller, in the case of negative numbers) can be stored in a Long. The Visual Basic String data type, on the other hand, takes up a different amount of memory depending on how much text is stored in it. A small amount of text (such as the word “Hello”) stored in a String variable would only take up a small amount of memory whereas the string variable with all of Shakespeare’s sonnets stored in it would take up considerably more memory.

First
Next

Choosing Data Type

The first question that needs answering is why a data type is important. Under the hood, data types are important because different data types are stored in different amounts of memory. As a VBScript programmer, you don’t need to be concerned with this sort of detail, but it’s useful to know that one data type might take more or less memory than another, which is one of the reason Visual Basic developers will choose one data type over another – the less memory taken up, the better. Choosing a specific data type is also important to a Visual Basic developer because it helps make the program easier to understand. When you know what data type a variable or parameter is, you also know the limitations on what kind of data is meant to be stored in that variable.

First
Next

What is Variant?

The reason is that in order to fully understand the behavior of the Variant, it is essential that you understand that the Variant is merely a ‘container’ for several different data types. Each of the Visual Basic data types that shall be listed later in a post - can be stored inside of the Variant as a subtype. A Variant’s subtype changes automatically depending on what kind of value is stored in it or you can manually set the subtype with one of the VBScript conversion feature. This becomes especially important when your VBScript programs need to interact with COM components that my have been written in VB or another COM-enabled language, such as C++ or Delphi.

First
Next

Visual Basic Data Types

Strictly speaking, VBScript only has one data type: the variant. The variant is a special data type that can store many different subtypes. I’ll get to the Variant data type in the next few posts, but first I need to discuss the data types of VBScript’s parent language, Visual Basic. You may be wondering why we need to discuss another language’s data type when VBScript only supports the Variant. This is currently a legitimate question.

Next

Always Use Comments

When writing code, strive to make it self documenting. You can do this by following the guidelines that I gave in related posts. However, self documenting code is elusive quarry. Like the pot of gold at the end of the rainbow, you can never quite reach it, even though it seems to close. The remedy for this is good comment. Most important thing for you to know is that what separates a good comment from a bad comment?

Generally speaking, a good comment operates at the level of intent. A good comment answers the questions, “What was the programmer trying to do with this code? Where does this code fit in with the overall scheme of the script? Why does this code exist?” The answer to these questions, fill in the blanks that can never be filled by even the best self-documenting code. Good comments are also generally “paragraph-level” comments. Your code should be clear enough that you do not need a comment for every line, but a comment that quickly and clearly describes the purpose for a block of code allows a reader to scan through the comments rather then reading every line of code. The idea is to keep the person who might be reading your code from having to pore over every line to try and figure out why the code exists.

Bad comments are generally redundant comments, meaning they repeat what the code itself already tells you. Try to make your code as clear as possible so that you don’t need to repeat yourself with comments. Redundant comments tend to add clutter and do more harm then good. Reading the code tells you the ‘how’; reading the comments should tell you the ‘why’.

Finally, it’s a good idea to get into the habit of adding “tombstone” or “flower box” comments at the top of each file, module, class, and the procedure. These comments typically describe the purpose of the code, the date it was created, the original author, and a log of modification.

First

Easy-to-Read Scripting

Keep in mind the power that the visual layout of your code has on its clarity. Without reading a single word, you should be able to look at the indentations of the lines to see which ones are subordinate to others. Keep related code together by keeping them on consecutive lines. Separate blocks of unrelated code by putting a blank line between them. Even though the script engine will let you avoid putting multiple statements on the same line.

Use the line continuation character ( _ ) to break long lines into multiple shorter lines. The importance of a clean layout that visually suggests the logic of the code cannot be overemphasized.

First
Next

Multiple Purpose Variable

This is a common mistake of beginner and experienced programmers alike to use one variable for multiple purposes, but the fact that experienced programmers might have a bad habit does not make it any less bad. Each variable in your script should have exactly one purpose. It may be tempting to just declare a couple of generic variables with fuzzy names, and then use them for multiple purposes throughout your script – but don’t do it! This is one of the best ways to introduce very strange, hard to track down bugs into your scripts. Giving a variable a good name that clearly defines its purpose will help prevent you from using it for multiple purposes.

First
Next

Hungarian Variable Naming Convention

This is a bit out of scope of this discussion, but it bears mentioning nonetheless. The concept of variable data type will be discussed later. The Hungarian naming convention involves giving variable names a prefix that indicates what the scope and data type of the variable are intended to be. So as not to confuse matters, I have not been using the Hungarian convention in my posts, but you will find that most programmers prefer this convention. Properly used, it makes your programs more clear and easier to read and write.

First
Next

Descriptive Name to Procedures

When naming procedures, try to choose a name that describes exactly what the procedure does. If the procedure is a function that returns a value, indicate what the return value is in the function name (for example, GetUserName). Try to use good verb-noun combination to describe firstly, what action the procedure performs, and secondly, what the action is performed on (for example SearchDirectory, MakeUniqueFileName, or LoadSettings). Studies show that, since procedures are generally more complicated than variables, good procedure name tend to be longer than good variable names. Fifteen to thirty characters for a procedure name is perfectly acceptable (they can be a bit longer since you generally don’t type them nearly as much). If you are having trouble giving your procedure a good name, that might be an indication that the procedure is not narrow enough – a good procedure does one thing, and does it well.

That said, if you are writing scripts for your WebPages that will be downloaded to a user’s browser, it is something necessary to use shorter variable and procedure names. Longer names mean larger files to download. Even if you sacrifice some readability in order to make the file smaller, you can still make an effort to make the names as descriptive as possible.

First
Next

Descriptive Name to Variables

Giving the elements of your programs good names is one of the most important things you can do to ensure that your code will be readable and easily understood. Primarily, this applies to the names you give to variables and procedures.

When naming a variable, use a name that will make it clear what that variable is used for. Be careful using abbreviations, especially if you think programmers from other countries might need to read your code. Don’t make variable names too short, but don’t make them too long either (studies have shown that ten to sixteen characters is a good length, but ideal length is largely a matter of preferences). Even though VBScript is not case-sensitive, use mixed case (for example, UserName) to make it easier to distinguish multiple words within the variable name.

First
Next

Modularize Code

When you are writing code, you should constantly evaluate whether any given block of code might be better if you moved it to its own function or sub-procedure. Is the code you’re working on rather complex? Break it into procedures. Are you using lots of Ands and Ors in an If…End If statement? Consider moving the evaluation to its own procedure. Are you writing a block of code that you think you might need again 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.

First
Next

Favor Explicit Over 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?” Even though something is obvious in your mind at the moment you are typing in the code, that does not mean that it will be obvious to you six months from now, or to someone else tomorrow. Strive to make your code self-documenting, and where you fall short of that goal (which even the best programmers do – self-documenting code can be an elusive goal), use good comments to make things more clear.

First
Next

Expect the Unexpected

Always remember that anything can and will happen. Code defensively. You don’t need to obsess over 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. Whenever you’re about to perform an action or something, ask yourself, “What could go wrong here? What happens if the file is flagged Read Only? What happens if the database table does not have any records? What happens if the registry keys I was expecting aren’t there?” If you don’t know what might go wrong with a given operation, find out through research or trial and error. Don’t leave it up to your users to discover how gracefully your script reacts to the unexpected. A huge part of properly preparing for the unexpected is the implementation of proper error handling.

First
Next

Programming Guidelines / Techniques

It is a really good idea to start adopting good habits right from the beginning. Down the road, you continue to hone your programming skills and even learn multiple languages; these habits will serve you well. Your programs will be easier for you and your fellow programmers to read, understand, and modify, and they will have fewer bugs. When you first get started writing code, you have to concentrate so hard on getting the syntax correct for the computer that its easy to lose sight of the things you need to do to make sure your programs are human friendly as well. However, diligence in this area will pay big dividends:

Next

Lahore City

Lahore City is the Capital of the Punjab, the largest province of Pakistan by population.

Geography of Lahore City

Lahore City is surrounded on the north and west by the Sheikhupra District, on the east by Wagah, on the south by Kasur District. The Ravi River flows on the northern side of Lahore City.

Land Area of Lahore City

Lahore City covers a land area of one thousand seven hundred and seventy five square kilometers, which is growing with the passage of time.

Population of Lahore City

As per Government estimation in 2006, the population of Lahore City was roundabout 10 million, which makes it the second largest city in Pakistan. It is thought-out to be one of the 30 largest cities of the world.

Climate of Lahore City

The climate of Lahore City is extreme. The temperatures ascend to 40–45 °C during the months of May, June, and July. Heavy rainfall starts during the month of August. Temperatures can drop to -1 °C during the months of December, January, and February. The city’s maximum temperature ever recorded was 48.3°C, while lowest temperature ever recorded was -6.2°C.

Administrative Towns in Lahore City

Following are the administrative towns of Lahore City.

Aziz Bhatti Town, Ravi Town, Shalimar Town, Wagah Town, Data Ganj Baksh Town, Gulberg Town, Allama Iqbal Town, Samanabad Town, Nishtar Town, Lahore Cantt, Gulshan-e-Ravi, and Walton Cantt.

Famous Places in Lahore City

Following are some famous places of Lahore City.

Mall Road, Lahore Zoo, Assembly Hall, Governor House, Anarkali Market, Pace, Hafeez Center, Ichra Bazaar, Mazang, Minar-e-Pakistan, Lahore Museum, Golf Course, Gadhafi Stadium, Jinah Garden, Badshahi Mosque.

Main Hospitals in Lahore City

C.M.H. Hospital, China Hospital, Gulab Devi Hospital, Lahore Medicare Hospital, Punjab Institute Of Cardiology, Wapda Hospital Complex, Ganga Ram Hospital, Gulberg Hospital, Haq Orthopaedic Hospital, Ittefaq Hospital, Lady Willington Hospital, Masood Hospital, Shaukat Kahanum Memorial Hospital, Jinnah Hospital.

Main Hotels in Lahore City

Pearl Continental, Mirage Hotel, Holiday Inn City Center, Avari Lahore, Bravo Suits Hotel, Lahore Country Club, The Residency Hotel, Quick Continental Hotel, National Hotel, Ambassador Hotel, Shalimar Hotel, Orient Hotel, Regency Inn Hotel, Hotel Services International.

Main Libraries in Lahore City

Dayal Singh Trust Library, Defence Public Library Complex, Environment Data Resource Centre (EDRC), Punjab Public Library, Punjab University Library, Quaid-e-Azam Library.

Main Parks in Lahore City

Shalimar Garden, Changa Manga, Jallo Park, Jinnah Garden, Model Town Park. Iqbal Park.

Main Educational Institutes in Lahore City

Lahore University of Management Sciences (LUMS), University of Engineering & Technology (UET), Lahore College for Women University, Hajvery University, Punjab College of Commerce, Government College Lahore, FC College Lahore, The University of Lahore, Punjab University, University of Health Sciences, University of Central Punjab, Science College.

General Info about Lahore City

  • Lahore City is famous as the hub of hand-made carpet manufacturing in Pakistan.
  • Lahore City is one of the most accessible cities of Pakistan.
  • The Pakistan Railways headquarters is located in Lahore City.
  • Allama Iqbal International Airport is in Lahore City.
  • People in Lahore City understand English well and good besides Urdu and Punjabi.
  • Lahore City is known as the cultural heart of Pakistan.
  • In Pakistan, Lahore City is famous as ‘the City of Colleges’.
  • Lahore is known as the City of Gardens.
  • The most important session of the creation of Pakistan was held in Lahore in 1940.
  • In 1996, the Cricket World Cup final match was held at the Gaddafi Stadium in Lahore.
  • Lahore City hosts the country's largest information technology (IT) companies, which accounts for nearly seventy percent of Pakistan's software exports.
  • Lahore City is the second largest financial hub of Pakistan and has industrial areas including Kot Lakhpat.
  • World-famous Punjab University is located at Lahore City.
  • Lahore is the center of Pakistan's media and Arts scene.
  • Pakistan's film industry is based in the city and is called Lollywood.

Karachi City

Karachi City is the Capital of Sindh, the south eastern province of Pakistan.

Geography of Karachi City

Karachi City is situated in the south of Sindh, on the shoreline of the Arabian Sea. It contains mainly of smooth or rolling plains, with hills on Manora Island and the Oyster Rocks. The Arabian Sea beach shapes the southern coastline of Karachi. Solid mangroves and streams of the Indus delta can be found towards the south east side of the city. Towards the north and the west is Cape Monze located, locally known as Raas Muari, an area marked with projecting sea cliffs and rocky sandstone capes. Some superb beaches can also be found in this region.

Land Area of Karachi City

Karachi City extends over an area of three thousand five hundred and fifty square kilometers i.e. one thousand five hundred and sixty six square miles.

Population of Karachi City

Karachi City is the biggest city in Pakistan. It is the world's second largest city proper behind Mumbai in terms of the number of residents, which went almost ten million in the year 2002. As per an estimation in 2008, the population of Karachi City is about twelve and a half million. In terms of population, Karachi City is the twentieth largest city of the world. The City’s population is currently growing at about five percent per year.

Climate of Karachi City

Situated on the shoreline, Karachi City tends to have a moderately mild climate with low levels of average rainfall (around two hundred and fifty millimeters per annum), the bulk of which occurs during the months of July and August. Winters are mild and the summers are hot, however the closeness to the sea maintains moisture levels at a near-constant high and cool sea breezes reduce the heat of the summer months. Due to high level of warmth during the summer (ranging from thirty to forty four degrees Celsius from April to August), the winter months (November to February) are usually considered the best times to visit Karachi City. July, December and January have pleasant and gloomy weather. Highest ever recorded temperature of Karachi city is 47.8 °C (118.0 °F) and lowest is 5.0 °C (41.0 °F).

Towns in Karachi City

Following are the names of towns in Karachi City.

Baldia Town, Bin Qasim Town, Gadap Town, Saddar Town, Shah Faisal Town, Gulberg Town, Gulshan-e-Iqbal Town, Jamshed Town, Keamari Town, Korangi Town, North Nazimabad Town, New Karachi Town, Orangi Town, SITE Town, Landhi Town, Liaquatabad Town, Lyari Town, and Malir Town.

Famous Places in Karachi City

Following are some of the famous places in Karachi City.

National Museum of Pakistan, Pakistan Air Force Museum, Pakistan Maritime Museum, Sindh High Court, Sindh Assembly Hall, Karachi Port Trust (Old building), Governor House, Cape Mount, Clifton Beach, French Beach, Hawke's Bay, Kinara Beach, Manora Beach, Paradise Point, Russian Beach, Bohri Bazar, Bolton Market, Chanti Lane, Empress Market, Hyderi Market, Jama Cloth Market, Jodia Bazar, Kaghzi Bazar, Kapra Market, Area 51 Bowling Club, Beach View Club, City Sports Complex, Creek Club, Defence Authority Club, Golf Club Sea View, Hockey Club of Pakistan, KCCA Cricket Ground, KPT Sports Complex,

Main Hospitals in Karachi City

Labtest Hospital, Combined Military Hospital, Jinnah Postgraduate Medical Centre, National Institute of Cardiovascular Diseases, National Institute of Child Health, PNS Rahat, Karsaz, PNS Shifa, Shoukat Omer Memorial Hospital, Civil Hospital, Civil Hospital (Burns Centre), Nazimabad Chest Clinic, Ojah Institute of Chest Diseases, Police Hospital, Sindh Government Children Hospital, Sindh Institute of Skin Diseases, Sindh Institute of Urology and Transplantation (SIUT), Skin & Social Hygiene Centre, Social Security Hospital.

Main Hotels in Karachi City

Avari Towers Hotel, Beach Luxury Hotel, Carlton Hotel, Days Inn, Embassy Inn, Hotel Faran, Hotel Mehran, Marriott Hotel, Pearl Continental Hotel, Ramada Plaza - Airport Hotel, Sheraton Hotel & Towers, Grand Mercure Hotel, Dream World Hotel & Resorts.

Main Libraries in Karachi City

Al-Huda Library, Al-Firdous Baldia Public Library, Allama Iqbal Library, Board of Intermediate Karachi Library, Baba-e-Urdu Kutubkhana, Children Library, Faiz-e-Aam Library, Faran Club Library, Ghalib Library, Hashim Gazder Library, Hungooraabad Library, Ibrahim Ali Bhai Auditorium & Library, Iqbal Shaheed Library, Iqra Library, Jehangir Park Reading Room Library, KMC Library, Liaquat National Memorial Library, Lyari Municipal Library, Lyari Text Book Library, Mansoora Library, Moosa Lane Reading Room Library, Moulana Hasrat Mohani Library, Mujahid Park Library, National Book Foundation Library.

Main Parks in Karachi City

Aisha Park, Askari Park, Aziz Bhatti Park, Bagh Ibne Qasim, Frere Hall gardens, Beach View Park, Boat Basin Park, Coconut Park, Nishtar Park, Talimi Bagh, Nisar Shaheed Park, Zam Zam Park, Quaid-e-Azam Park, Quaid Mausoleum park.

Main Educational Institutes in Karachi City

Aga Khan University, Baqai Medical University, Dadabhoy Institute of Higher Education, DHA Suffa University, FAST-National University of Computer and Emerging Sciences, Fatima Jinnah Dental College, Greenwich University, Hamdard University, Indus Institute of Higher Education, Indus Valley School of Art and Architecture, Institute of Business & Technology, Institute of Business Management, Iqra University, Jinnah University for Women, Karachi Institute of Economics & Technology, Khadim Ali Shah Bukhari Institute of Technology (KASB), Meharban Jogari University, Mid asia Institute of Science & Technology, Mohammad Ali Jinnah University, Nazeer Hussain University, Pakistan Navy Engineering College, Shaheed Zulfikar Ali Bhutto Institute of Science & Technology, Sir Syed University of Engineering & Technology, Textile Institute of Pakistan, Ziauddin Medical University.

General Info about Karachi City

  • Karachi City is Pakistan's premier center of banking, industry, and trade.
  • Karachi City is the financial and commercial capital of Pakistan.
  • Karachi City serves as a major hub of higher education in South Asia, and the wider Islamic World.
  • Karachi City was the original capital of Pakistan until the construction of Islamabad City.
  • Founder of Pakistan, Mohammad Ali Jinnah, was born in Karachi City.
  • Karachi City claims highest per capita income in South Asia.
  • Most of Pakistan's public and private banks are headquartered on Karachi City.
  • Largest Stock Exchange of Pakistan is in Karachi City.
  • Branches of world-famous motor companies are in Karachi City.
  • Karachi City has one hundred and seventy eight union councils.
  • Jinnah International Airport is the largest and busiest airport of the country and is located in Karachi City.
  • Port of Karachi and the Port Qasim are the largest shipping ports of Pakistan and are located in Karachi City.
  • Karachi City is the one of the most rapidly growing cities in the world.

Quetta City

Quetta City is the Capital of the Balochistan, the largest province of Pakistan by land area.

Geography of Quetta City

Quetta city consists of a valley and is a natural fort, delimited as it is by grand hills on all sides. The surrounding hills have the booming names of Chiltan, Zarghun, Takatoo and Murdar, encircled by three different mountain ranges. Quetta City is north west of Karachi and Hyderabad, and south west of Islamabad and Rawalpindi. Quetta City is situated at an altitude of seventeen to nineteen hundred meters above sea level.

Land Area of Quetta City

Quetta City has a land area of two thousand six hundred and fifty square kilometers.

Population of Quetta City

As per non-governmental census in 2007, the population of Quetta City was approximately 7.6 million including 1.6 million Afghan immigrants. Population mostly consists of Pashto speaking people.

Climate of Quetta City

The climate of Quetta City is dry, and mountain air is energizing. Winter starts from the month of November and ends in the month of February. Snowfall is light, though it is not odd to have one in March. Quetta City has minimum winter temperatures ranging well below freezing point and as low as -18˚C. Conveniently the educational institutes are closed in winter due to temperature below freezing point. Quetta City can show off the best spring and autumn in Pakistan. Although summers are warm, the maximum temperature hardly exceeds 32 degrees Celsius (90 degrees Fahrenheit). The evenings are very pleasant, distinguished by a cool breeze that springs to life an hour or two after sunset. Fans are necessary during May and August. Quetta City does not have a rich rainy season during monsoon time. However, it rains during winter.

Towns in Quetta City

Quetta City has several small housing areas, few of which are following.

Gulistan Town, Quetta Cantt, Satellite town, Jinnah Town, Samugli Housing Scheme.

Notable Places Near Quetta City

Following are some famous places near Quetta City.

Pishin Valley, Hanna lake, Askari Park, Hazarganji Chiltan National Park.

Main Hospitals in Quetta City

Children Hospital, Civil Hospital, Bolan Medical Complex Hospital, Lady Dufferin Hospital , Helper's Eye Hospital , Fatima Jinnah T.B. Sanitorium, Cenar Hospital.

Main Hotels in Quetta City

Quetta Serena, Fabbs Hotel, Bloom Star Hotel, PTDC Taftan, PTDC Ziarat.

Main Libraries in Quetta City

Balochistan University Library, Central Library, Baluchistan Provincial Assembly Library.

Main Educational Institutes in Quetta City

Balochistan Institute of Technology, Dare Arqam School of Islam & Modern Sciences, Balochistan University of Information Technology & Engineering and Management Sciences, Command and Staff College, Sardar Bahadur Khan Women University, University of Balochistan, Pharmacy Department Of Balochistan University, Iqra University, F.G Degree College Quetta Cantt, Model Public School & college, Tameer-i-Nau public college, Government College of Technology Balochistan, Army public school and college, Bolan Medical College Quetta,

General Info about Quetta City

  • Quetta City is a variation of kwatkot, a Pashto language word, which means ‘fort’.
  • Quetta City is a vital marketing and communications centre between Afghanistan and Pakistan.
  • Quetta City is famous as the fruit basket of Pakistan.
  • Football is very popular among the people of Quetta City.
  • Quetta City Airport is the fourth highest airport of Pakistan in terms of altitude.
  • Quetta City was first mentioned in the 11th century when it was captured by Mahmud Ghaznawi.
  • Quetta City was completely destroyed in an earthquake of 7.1 magnitudes on 31 May 1935.
  • Thousands of orchards can be found in Pishin Valley, a valley, 50 km far from Quetta City.
  • Quetta City is the ninth largest city of Pakistan by population.
  • Quetta City was the outer edge of Qandahar until it was captured by the British in Second Afghan war.
  • Quetta City is one of those cities that are mostly visited by tourists from abroad.
  • Hazarganji Chiltan National Park, spread over 32500 acres is located 20 km far from Quetta City.

Top-Down Code vs. Event Driven Code

We write some code, save it in a script file, and use the Window Script Host to execute the script. The Script Host starts executing at the first line and continues to the last line. If a script file contains some procedure definitions (such as our GetUserName function), then the Script Host will only execute those procedures if some other code calls them. Once the Script Host reaches the last line of code, the lifetime of the script ends.

To-Down programs are very useful for task-oriented scripts. For example, you might write a script to search your hard drive for all the files with the extension .DOC and copy them to a backup directory. Or you might write a script that gets executed every time Windows starts that randomly chooses a desktop wallpaper bitmap file for the session of Windows. Top-Down programming is perfect for these kinds of scripts.

Event driven code is different, and is useful in different contexts. As the name implies, event-driven code only gets executed when a certain "event" occurs. Until that event occurs, the code won't get executed. If a given event does not occur during the lifetime of the script, the code associated with the event won't get executed at all. If an event occurs, and there's no code associated with the event at all, the event is essentially ignored.

Event driven programming is the predominant paradigm in Windows programming. Most Windows programs that you use every day were written n the event driven model. This is because of the graphical nature of Windows programs. In a graphical user interface (GUI), you have all sort of buttons drop-down lists, fields in which to type text, etc. Every time a user clicks a button, chooses an item in a list, or types some text into a field, an event is raised within the script. The person wrote that program may or may not have decided to write code in response to that event.

When a GUI-based program starts, there is almost always some top-down style code that executes first. This code would do things like connect to a database, prompt the user for a name and password, load some settings from a file or the Windows registry, etc. Then a form typically comes up. The form contains the menus, buttons, lists, and fields that make up the user interface of the program. At that point, the top-down style code is done, and the program enters what is knows as wait state. No code is executing at this point. The program is just sitting there, waiting for the user to do something. From there on in, it's all about events.

Lets say the user clicks on a button. Now the program comes to life again. The program raises the "Click" event for the button that the user clicked. The code that is attached t the event starts to execute, performs some operations, and when it's finished, the program returns to its wait state. Until another event occurs, the program just sits there.

As for as VBScript, the event driven model is used in scripting for the World Wide Web. The scripts that run inside of HTML pages are all based on events. One script might execute when the page is loaded. Another script might execute when the user clicks on a button or graphic. These "mini scripts" are embedded in the HTML file, and are blocked out in a syntax very similar to the one we used to define the GetUserName function in some other posts.

Let us see an example. Type the following code into your text editor, save the file with a HTML extention, and then select Open from the File menu in Internet Explorer 4.0 or higher to open the file.


<html>
<head>
<Script language="VBScript">
Sub ButtonClicked
window.alert("You clicked the button.")
End Sub
</Script>
</head>
<body>
<Button name="SomeButton" type="Button" onclick="ButtonClicked">
Click Me
</Button>
</body>
</html>

Third Advantage of Procedures

When code is isolated into its own procedure, it greatly reduces the effects of changes to that code. This goes back to the idea of the black box. As long as the procedure itself maintains its predictable inputs and outputs, changes to the code inside of a procedure are insulated from harming the code that calls the procedure. If we decide we don't want to use a loop anymore in the GetUserName function, we can change the code to only ask the user his name once instead of five times. The code that calls the GetUserName function won't care.

First

Second Advantage of Procedures

When you call a procedure to perform a task than writing the code "inline," it makes that code easier to read and maintain. Increasing the readability, and therefore the maintainability, of your code is a good enough reason by itself to break a block of code out into its own procedure. Not including the comments and blank lines, the GetUserName function contains 19 lines of code. By taking these 19 lines and moving them to their own procedure, we reduced the code from which we moved it by 19 lines. Less Code + good procedure name = easier to read. If ever you're writing some code that is getting rather long, consider breaking one or more sections of it out into their own functions or sub procedures.

First
Next

First Advantage of Procedures

Code such as the code we put in the GetUserName function can be thought of as "generic," meaning that it can be applied to a variety of uses. Once you have a discreet, well defined, generic function such as GetUserName, you can reuse it any time you wish to prompt the user for their name. Once you've written a well-tested procedure, you never have to write that code again. Any time you need it, you just call the procedure. This is knows as Code Reuse.

First
Next

GetUserName Function

Function GetUserName
'Prompts the user for his name. If the user refuses to provide
''his name five times, we give up and return a zero-length string.
Dim UserName
Dim TryAgain
Dim LoopCount
LoopCount = 1
Do
TryAgain = "No"
UserName = InputBox("Please enter your name:")
UserName = Trim(UserNAme)
If UserName = " " Then
If LoopCount > 5 Then
UserName = " "
TryAgain = "No"
Else
MsgBox "You must enter your name."
TryAgain = "Yes"
End If
LoopCount = LoopCount + 1
Loop While TryAgain = "Yes"
GetUserNAme = UserName
End Function

Finally, notice how, in the second to last line, we treat the function name GetUserName as if it were a variable. When using 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.

Let's take a look at some code that uses the GetUserName function.

Dim Greeting
Din AnyName
AnyName = GetUserName
If Trim(AnyName( <> " " Then
Greeting = "Hello, " & AnyNAme & " Glad to meet you."
Else
Greeting = "I/m glad to meet you, but I wish I knew your name."
End If
MsgBox Greeting

If you are using the Windows Script Host to execute this code, keep in mind that the above code and the GetUserName function itself must be in the same .vbs file. As you can see, calling the GetUserNAme function is pretty straightforward. Once you have written a procedure, calling it is no different than calling a built-in VBScript procedure.

Breaking your code into modular procedures is very good habit to pick up.

First
Next

Comment in the Procedure

Function GetUserName
'Prompts the user for his name. If the user refuses to provide
'his name five times, we give up and return a zero-length string.
Dim UserName
Dim TryAgain
Dim LoopCount
LoopCount = 1
Do
TryAgain = "No"
UserName = InputBox("Please enter your name:")
UserName = Trim(UserNAme)
If UserName = " " Then
If LoopCount > 5 Then
UserName = " "
TryAgain = "No"
Else
MsgBox "You must enter your name."
TryAgain = "Yes"
End If
LoopCount = LoopCount + 1
Loop While TryAgain = "Yes"
GetUserNAme = UserNAme
End Function

We also added a comment to the beginning of the procedure to describe what it does. Notice that the comment does not describe how the function does what it does, only what it does. The code that uses this function does not care how the function accomplishes its task - it only cares about inputs, outputs, and predictability. It is very important that you add comments such as this to the beginning of your procedure, since they make it easy to determine what the function does. This comment also performs one other valuable service to you and any other developer who wants to call this function: it mentions that the function may return an zero-length string if the user does not enter his name. It is important that a programmer knows the possible range of return values so they can right code to deal with those contingencies.

First
Next

Why We Added The Loop Counter?

Function GetUserName
'Prompts the user for his name. If the user refuses to provide
''his name five times, we give up and return a zero-length string.
Dim UserName
Dim TryAgain
Dim LoopCount
LoopCount = 1
Do
TryAgain = "No"
UserName = InputBox("Please enter your name:")
UserName = Trim(UserNAme)
If UserName = " " Then
If LoopCount > 5 Then
UserName = " "
TryAgain = "No"
Else
MsgBox "You must enter your name."
TryAgain = "Yes"
End If
LoopCount = LoopCount + 1
Loop While TryAgain = "Yes"
GetUserNAme = UserNAme
End Function

The reason we added the loop counter to the code is that our goal is to create a perfect black box. A perfect black box is very predictable as possible. The more predicable it is, the less the code that calls the procedure has to worry about it. If the user is being difficult and does not want to enter his name, we don't want to keep looping around forever., asking again and again. So after asking five times, the function gives up and returns a zero-length string.

First
Next

Code Inside The Function

Function GetUserName
'Prompts the user for his name. If the user refuses to provide
''his name five times, we give up and return a zero-length string.
Dim UserName
Dim TryAgain
Dim LoopCount
LoopCount = 1
Do
TryAgain = "No"
UserName = InputBox("Please enter your name:")
UserName = Trim(UserNAme)
If UserName = " " Then
If LoopCount > 5 Then
UserName = " "
TryAgain = "No"
Else
MsgBox "You must enter your name."
TryAgain = "Yes"
End If
LoopCount = LoopCount + 1
Loop While TryAgain = "Yes"
GetUserNAme = UserNAme
End Function

The code inside the function is very similar to the code I used in the discussion of loops. I have introduced one new element, though: the LoopCount variable. I am using this variable to count the number of times we go through the loop. Before we start the loop, we initialize LoopCount with the numeric value of zero. Then, at the beginning of each loop, we increment the value of LoopCount by 1. If we go through the loop more than five times without the user entering his name, we stop asking and set the user name to a blank string (represented by " ").

First
Next

Function Explained

Function GetUserName
'Prompts the user for his name. If the user refuses to provide
''his name five times, we give up and return a zero-length string.
Dim UserName
Dim TryAgain
Dim LoopCount
LoopCount = 1
Do
TryAgain = "No"
UserName = InputBox("Please enter your name:")
UserName = Trim(UserNAme)
If UserName = " " Then
If LoopCount > 5 Then
UserName = " "
TryAgain = "No"
Else
MsgBox "You must enter your name."
TryAgain = "Yes"
End If
LoopCount = LoopCount + 1
Loop While TryAgain = "Yes"
GetUserNAme = UserNAme
End Function

The first thing to take note of here are the first and last line. The first line defines the beginning of the function and gives it a name. The last line defines the end of the function. Based on our earlier discussion of code blocks, this should be a familiar convention by now. In a sense, a procedure is nothing but a special kind of code block. We have to tell the script engine where it begins, and where it ends. Notice that we have given the function a clear, useful name that precisely described what this function does. Giving your procedure good name is a key to writing programs that are easy to read and maintain.

First
Next

Procedure and Subprocedure

First, though, let's get some terminology straight. "Procedure" is a generic term that can be used to describe either a function or a sub function. I touched some of this confusing terminology earlier, but a function is a procedure that returns a value. Trim ( ) is a function. You pass it some text, and it returns the same text back to you, but with the leading trailing spaces stripped off. Functions do not always require input, but they often do.

A sub procedure is a procedure that does not return a value. We have been using MsgBox ( ) as a sub procedure in other posts. We pass it some text, and it displays a message on the screen. It does not return any kind of value to our code. All we need to know is that it did what we asked it to do. Like functions, procedure may or may not require input.

First
Next

Procedure

The most basic kind of black box programmers use to achieve modularity is the procedure. A procedure is a set of code that ideally performs a single function. I have used many procedures in previous posts. Some procedures require input, some don't. Some of these procedures return a value, some don't. But all of the procedures I mentioned in other posts (MsgBox ( ), InputBox ( ),, etc.) are black boxes. They perform one single well defined function, and they perform it without your having to worry about how they perform their respective functions.

Let's move forward to learn how to extend the VBScript language by writing our own procedure.

First
Next

Black Box

A black box is any kind of device that has a simple, well defined interface and that performs some discrete, well defined function. A black box is so called because you don't need to see what is going on inside of it. All you need to know is what it does, what its inputs are, and sometimes what its outputs are. We encounter black boxes every day. A wrist watch is a good example. A typical watch has some buttons or dials with which you can set the time (the inputs), and a face that you can read to determine the time at any given moment (the out puts). You don't need to know or care how all the gears and gizmos inside the watch are put together in order for the watch to be useful to you. Unless you are an aficionado or collector of watches, you don't really care if it has quartz movement or if there's a small rodent running around inside to keep the watch ticking. It's a black box. All that's important to you are that it works, and that you understand its inputs and outputs.

First
Next

Modularization

Modularization is the process of organizing your code into modules., which we 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, and easier for you and your fellow programmers to maintain. When you divide your code into modules, your goal is to create what are known as black boxes.

First
Next

Organizing and Reusing Code

When you sit down to write a script that will do something useful, chances are your code is going to get a bit more complex. As you add more and more code, it becomes harder and harder to read it all in one chunk. If printed on paper, your script would probably stretch across multiple pages. As the code gets more and more complex, it becomes easier and easier for bugs to creep in, which makes it harder and harder to find and fix those bugs. The most common technique that programmers use to manage complexity is called modularization. That's a big, fancy word, but the concept is simple really.

Next

Your Ability as a Financial Manager

If you become a financial manager, your ability to adapt to change, raise funds, invest in assets, and manage wisely will affect the success of your firm and, ultimately, the overall economy as well. To the extent that funds are mis-allocated, this growth of the economy will be slowed. When economic wants are unfulfilled, this mis-allocation of funds may work to the detriment of society. In an economy, efficient allocation of resources is vital to optimal growth in that economy; it is also vital to ensuring that individuals obtain satisfaction of their highest levels of personal wants. Thus, through efficiently acquiring, financing, and managing assets, the financial manager contributes to the firm and to the vitality and growth of the economy as a whole.

First

Impact of External Factors on Financial Manager

Today, external factors have an increasing impact on the financial manager. Heightened corporate competition, technological change, volatility in inflation and interest rates, worldwide economic uncertainty, fluctuating exchange rates, tax law changes, and ethical concerns over certain financial financial dealings must be dealt with almost daily. As a result, finance is required to play an ever more vital strategic role within the corporation. The financial manager has emerged as a team player in the overall efforts of a company to create value. The "old ways of doing things" simply are not good enough in a world where old ways quickly become obsolete. Thus, today's financial manager must have the flexibility to adapt to the changing external environment if his or her firm is to survive.

First
Next

Role of a Financial Manager

The financial manager plays a dynamic role in a modern company's development . This has not always been the case. Until around the first half of the 1900s financial managers primarily raised funds and managed their firms' cash positions - and that was pretty much it. In the 1950s, the increasing acceptance of present value concepts encouraged financial managers to expand their responsibilities and to become concerned with the selection of capital investment projects.

Next

Operator Precedence

When more than one operation occurs in an expression they 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.

This is the set order in which operators occur (operators in brackets have the same precedence).

^,-,(*,/),\,Mod,(+,-),
&,
=,<>,<,>,<=,>=,Is,
Not, And, Or, Xor, Eqv, Imp

This order can be overridden by using parentheses. Operations in parentheses are evaluated before operations outside the parentheses, but inside the parentheses, the normal precedence rules apply.

If we look at two statements:

A = 5+6+7+8
A = (5+6) * (7+8)

According to operator precedence, multiplication is preferred before addition, so the top line gives A the value 55. By adding parentheses, we force additions to be evaluated first and A becomes equal to 165.

First

Types of Operators

There are different types of operators and they each serve a specific purpose.

1. The assignment ( = ) operator is the is the most obvious and is simply used for assigning a value to a variable or property.
2. The arithmetic operators are all used to calculate a numeric value, and are normally used in conjunction with the assignment operator and / or one of the comparison operators.
3. The concatenation operators are used to concatenate ("Join together") expressions.
4. The comparison operators are used for comparing variables and expressions against other variables, constants, or expressions.
5. The logical operators are used for comparing variables and expressions against other variables; all logical operators can also be used as bitwise operators.
6. The bitwise operators are used for comparing binary values bit-by-bit; all bitwise operators can also be used as logical operators.

First
Next

Operators

An operators 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 A and B and save the result in variable C. These variables are the operands and to find the difference you use the subtraction operator like this:

C = A - B

Here I used the assignment operator ( = ) to assign the difference between A and B, which was found by using the subtraction operator ( - ).

Operators are one of the single-most important parts of any programming language. Without them, you would not be able to assign values to variables or perform calculations and comparisons! It would be a bit like a bicycle without pedals ...

Types of Operators
Operator Precedence

For...Next Loop

Now we'll take a quick look at another kind of loop: the For...Next loop. In this kind of loop, we don't need to worry about infinite loops. This is because the loop is predefined to only execute a certain number of times. Here's a simple example:

Dim Index
MsgBox "Let's count to five. Ready?"
For Index = 1 to 5
MsgBox Index
Next
MsgBox "Wasn't that fun?"

The beginning loop block is defined by the For statement, and the end is defined by the Next statement. This loop will go around exactly five times. The line For Index = 1 to 5 essentially tells the script engine, "Execute this block of code as many times as it takes to count from 1 to 5, and use the Index variable to keep track of your counting. When we've gone through this code five times, stop looping and move on." Notice that every time the loop goes around (including the first time through), Index equal 1, the second time through it equals 2, and so on up to 5. It's important to note that after the loop is finished, the value of the Index variable will be 6, one number higher than the highest value in our For statement. This occurs because the Index variable is incremented at the end of the loop, after which the For statement tests the value of Index to see if it is necessary to loop again.

It's difficult to express the real-world usefulness of the For...Next loop without opening a can of worms on a lot of other subjects, but keep in mind that it is often used to traverse some sort of finite piece of data, such as a word, or a text file. For example, the word "elephant" has exactly eight letters. If you first calculate the number of letters in the word "elephant", you could use that number to drive a For...Next loop. Below is a simple example that uses the VBScript Len ( ) function to calculate the length of the word "elephant." Inside the loop, it uses the Mid ( ) function to pull one letter of the word "elephant" at a time.

Dim Index
Dim WordLength
WordLength = Len("elephant")
For Index = 1 to WordLength
MsgBox Mid("elephant", Index, 1)
Next
MsgBox "elephant"

First

President of Pakistan Pervez Musharraf Resigned

Pervez Musharraf, the President of Pakistan, today on the 18th of August 2008, resigned from his presidency because of the extreme pressure of the fear of impeachment by the Democratic Ruling Elite. He was in a state of fear of being given the capital punishment under the Article-6 of the Constitution of Pakistan. The Pakistan's Democratic Ruling Elite had offered him safe passage as a reward of his resignation. Former President of Pakistan, Pervez Musharraf, ruled over Pakistan for approximately nine years by the use of every illegal mean he could. People of Pakistan are dancing with joy and happiness after that Pakistan got rid of a person who is hated every where in the country because of his cruelty and serial killing.

Loop While in Do...Loop Code

Dim Greeting
Dim UserName
Dim TryAgain
Do
TryAgain = "No"
UserName = "InputBox("Please enter your name:")
If Trim(UserName) = " " Then
MsgBox "You must enter your name."
TryAgain = "Yes"
Else
Greeting = "Hello. " & UserName & ", it's a pleasure to meet you."
End If
Loop While TryAgain = "Yes"
MsgBox Greeting

Do
TryAgain = "No"
UserName = "InputBox("Please enter your name:")
If Trim(UserName) = " " Then
MsgBox "You must enter your name."
TryAgain = "Yes"
Else
Greeting = "Hello. " & UserName & ", it's a pleasure to meet you."
End If
Loop While TryAgain = "Yes"
MsgBox Greeting

Now we encounter the end of our loop block. What this Loop line is essentially telling the script engine is "If the TryAgain variable equals "Yes" at this point, then go back up to Do line and execute all that code over again." If the user entered their name, then the TryAgain variable will be equal to "No". Therefore, the code will not loop again, and will continue on to the last line:MsgBox Greeting, which we've seen before.

If the user did not enter their name, then TryAgain would be equal to "Yes", which would mean that the code would jump back up to the Do line again. This is where the re-initialization of the TryAgain variable to "No" is essential. If we don't reset the value of TryAgain, then there's no way for TryAgain to ever equal anything but "Yes". If TryAgain always equals "Yes", then the loop keeps going around and around forever. This is disaster for your script.=, and for your user.

First
Next

Trim Function in Do...Loop Code

Dim Greeting
Dim UserName
Dim TryAgain
Do
TryAgain = "No"
UserName = "InputBox("Please enter your name:")
If Trim(UserName) = " " Then
MsgBox "You must enter your name."
TryAgain = "Yes"
Else
Greeting = "Hello. " & UserName & ", it's a pleasure to meet you."
End If
Loop While TryAgain = "Yes"
MsgBox Greeting

Do
TryAgain = "No"
UserName = "InputBox("Please enter your name:")
If Trim(UserName) = " " Then
MsgBox "You must enter your name."
TryAgain = "Yes"
Else
Greeting = "Hello. " & UserName & ", it's a pleasure to meet you."
End If

Now we are testing our input. The line IF Trim(UserName) = " " Then tests to see if the user typed in their name. If they typed something in, the code immediately after the Else line will execute. If they did not (or if they clicked the Cancel button), then the UserName variable will be empty, and the code after the If line will execute instead. If the user did not type in their name, we display a message informating them that they have done something our script did not like. Then we set the TryAgain variable (our "control" variable) to "Yes". This ensures that the loop will go around again, and then we'll ask the user for their name again.

If the user did type their name, then we initialize our familiar Greeting variable. Note that in this case, we do not change the value of the TryAgain variable. This is because there is no need to loop around again - the user has obliged us and entered their name. The value of TryAgain is already equal to "No", so there's no need to change it.

First
Next

Input in Do...Loop Code

Dim Greeting
Dim UserName
Dim TryAgain
Do
TryAgain = "No"
UserName = "InputBox("Please enter your name:")
If Trim(UserName) = " " Then
MsgBox "You must enter your name."
TryAgain = "Yes"
Else
Greeting = "Hello. " & UserName & ", it's a pleasure to meet you."
End If
Loop While TryAgain = "Yes"
MsgBox Greeting

Do
TryAgain = "No"
UserName = "InputBox("Please enter your name:")

This should look familiar. We are using the InputBox function to ask the user for their name. We store the return value from the function in the UserName variable. Whatever the user types in, if anything, will be stored in this variable. Put another way, our script is receiving some external input - and remember that I said input is always unpredictable.

First
Next

Control Variable in Do...Loop Code

Dim Greeting
Dim UserName
Dim TryAgain
Do
TryAgain = "No"
UserName = "InputBox("Please enter your name:")
If Trim(UserName) = " " Then
MsgBox "You must enter your name."
TryAgain = "Yes"
Else
Greeting = "Hello. " & UserName & ", it's a pleasure to meet you."
End If
Loop While TryAgain = "Yes"
MsgBox Greeting

Do
TryAgain = "No"

Here we are initializing our "control" variable . We call it the "control" variable because this variable will ultimately control whether or not the loop loops around again. We want to initialize this variable to "No" so that, by default, the loop will not loop around again. Only if a certain something occurs inside the loop will we set TryAgain to "Yes". This is yet another strategy in our ever-vigilant desire to expect the unexpected.

First
Next

Do in Do...Loop Code

Dim Greeting
Dim UserName
Dim TryAgain
Do
TryAgain = "No"
UserName = "InputBox("Please enter your name:")
If Trim(UserName) = " " Then
MsgBox "You must enter your name."
TryAgain = "Yes"
Else
Greeting = "Hello. " & UserName & ", it's a pleasure to meet you."
End If
Loop While TryAgain = "Yes"
MsgBox Greeting

Do

This starts the loop. This tells the script engine that we 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...End If code block: the script engine expects the block to be defined with beginning and ending statements. I'll get more into this later but take a note the Do statement on a line all by itself means that the loop will execute at least once. Even if the Loop While statement at the end of the block does not result in a loop-around back to the Do line, the code inside this block is going to execute at least one time.

First
Next

Controlling Loop in VBScript

Dim Greeting
Dim UserName
Dim TryAgain
Do
TryAgain = "No"
UserName = "InputBox("Please enter your name:")
If Trim(UserName) = " " Then
MsgBox "You must enter your name."
TryAgain = "Yes"
Else
Greeting = "Hello. " & UserName & ", it's a pleasure to meet you."
End If
Loop While TryAgain = "Yes"
MsgBox Greeting

We are using the TryAgain variable to control the loop. The loop starts at the word Do. At the End of the loop, if the TryAgaon variable equals "Yes", then the code starting at the word Do will execute again. Notice that at the top of the loop we initialize the TryAgain variable to "No". It is essential that this initialization take place inside the loop (that is, between the Do and Loop statements). This way the variable is re-initialized every time a loop occurs. If we did not do this, we would end up with what's called an infinite loop.

Infinite loops are undesirable, and whenever you code any kind of loop, you need to take measures to make sure they do not produce an infinite loop. As the term suggests, an infinite loop is one that never stops. Remember that the computer will only do what your script tells it to do. If you tell it to keep looking forever, it will. As long as the loop keeps looping, the code that comes after the loop never gets executed.

Let us move on to a line by line explanation of the code.

First
Next

Do...Loop

First we're going to use the Do...Loop while construct to repeatedly execute a block of code until a certain condition is met. Take a look at this modification of our example script:

Dim Greeting
Dim UserName
Dim TryAgain
Do
TryAgain = "No"
UserName = "InputBox("Please enter your name:")
If Trim(UserName) = " " Then
MsgBox "You must enter your name."
TryAgain = "Yes"
Else
Greeting = "Hello. " & UserName & ", it's a pleasure to meet you."
End If
Loop While TryAgain = "Yes"
MsgBox Greeting

Notice the block of code that starts with the word Do and ends with the line that starts with the word Loop. The indentation should make this code block easy to identify. This is the definition of our loop. The code inside the loop will keep executing until at the end of the loop, the TryAgain variable equals "No".

First
Next

Looping in VBScript

Branching in VBScript allows you to tell the script to execute some lines of code, but not others. Looping in VBScript, on the other hand, allows you to tell the script to execute some lines of code over and over again. This is useful in two situations: when you want to repeat a block of code until a condition is True or False, and when you want to repeat a block of code a defined number of times.

First
Next