Tải bản đầy đủ - 0 (trang)
Figure 7-2. An InputBox dialog box

Figure 7-2. An InputBox dialog box

Tải bản đầy đủ - 0trang

returns the leftmost number characters in string, and:

Right(string, number)

returns the rightmost number characters in string. For instance:

MsgBox Right("Donna Smith", 5)

displays the string Smith.

The syntax for Mid is:

Mid(string, start, length)

This function returns the first length number of characters of string, starting at

character number start. For instance:


returns the string xls. If the length parameter is missing, as in:


the function will return the rest of the string, starting at start.

The InStr, InStrRev functions

The syntax for the very useful InStr function is:

Instr(Start, StringToSearch, StringToFind)

The return value is the position, beginning at Start, of the first occurrence of

StringToFind within StringToSearch. If Start is missing, then the function starts

searching at the beginning of StringToSearch. For instance:

MsgBox Instr(1, "Donna Smith", "Smith")

displays the number 7, because "Smith" begins at the seventh position in the string

"Donna Smith."

The InStrRev function is analogous to InStr but searches backwards through the

StringToSearch string.

The Replace function

This very useful function (not available in Excel 97) is used to replace a substring in a

string by another string. For instance, the code:

MsgBox Replace("the car is red", "red", "blue")

displays the string "the car is blue".

The Str and Val functions


The Str function converts a number to a string. For instance:


returns the string 123. Conversely, the Val function converts a string that represents a

number into a number (so that we can do arithmetic with it, for instance). For example:


returns the number 4.5 and:

Val("1234 Main Street")

returns the number 1234. Note, however, that Val does not recognize dollar signs or

commas. Thus:


returns 0, not 12.00.

The Trim, LTrim, and RTrim functions

The LTrim function removes leading spaces from a string. Similarly, RTrim removes

trailing spaces, and Trim removes both leading and trailing spaces. Thus:




returns the string extra.

The String and Space functions

The String function provides a way to quickly create a string that consists of a single

character repeated a number of times. For instance:

sText = String(25, "B")

sets sText to a string consisting of 25 Bs. The Space function returns a string consisting

of a given number of spaces. For instance:

sText = Space(25)

sets sText to a string consisting of 25 spaces.

The Like operator and StrCmp function

The Like operator is very useful for comparing two strings. Of course, we can use the

equal sign, as in:

string1 = string2

which is true when the two strings are identical. However, Like will also make a caseinsensitive comparison or allow the use of pattern matching. The expression:


string Like pattern

returns True if string fits pattern, and False otherwise. (Actually, the expression

can also return Null.) We will describe pattern in a moment.

The type of string comparison that the Like operator uses depends upon the setting of the

Option Compare statement. There are two possibilities, one of which should be placed

in the Declarations section of a module (in the same place as Option Explicit):

Option Compare Binary

Option Compare Text

Note that the default is Option Compare Binary.

Under Option Compare Binary, string comparison is in the order given by the ANSI

character code, as shown here:

Under Option Compare Text, string comparison is based on a case-insensitive sort

order (determined by your PC's locale setting). This gives a sort order as shown here:

By the way, the last item in the Text sort order is the "]" character, with ANSI value 91.

This is useful to know if you want to place an item last in alphabetical order—just

surround it with square brackets.

The pattern-matching features of the Like operator allow the use of wildcard characters,

character lists, or character ranges. For example:


Matches any single character


Matches zero or more characters


matches any single digit (0-9)


Matches any single character in charlist


Matches any single character not in charlist

For more details, check the VBA help file.


The StrCmp function also compares two strings. Its syntax is:

StrComp(string1, string2 [, compare])

and it returns a value indicating whether string1 is equal to, greater than, or less than

string2. For more details, check the VBA help file.

7.4 Miscellaneous Functions and Statements

Of the wealth of functions offered by the VBA language, we'll focus on the Is... functions to

determine an attribute of a variable or object, the conversion functions, and two functions, IIf

and Switch, that return a conditional result.

7.4.1 The Is Functions

VBA has several Is functions that return Boolean values indicating whether or not a certain

condition holds. We have already discussed the IsMissing function in connection with optional

arguments. Here are some additional Is functions. The IsDate function

This function indicates whether an expression can be converted to a date. It also applies to a cell,

in which case it evaluates the contents of the cell. If the contents represent a valid date, the

function returns True. For instance, the code:


will return True if the contents of cell F3 represent a date. The IsEmpty function

This function indicates whether a variable has been initialized or whether a worksheet cell is

empty. For example, the code:

If IsEmpty(Range("A1")) Then . . .

tests whether or not cell A1 is empty. The IsNull function

This function is used to test whether a variable is Null (that is, contains no data). Note that code

such as:

If var = Null Then

will always return False because most expressions that involve Null automatically return

False. The proper way to determine if the variable var is Null is to write:

If IsNull(var) Then The IsNumeric function


This function indicates whether an expression can be evaluated as a number or whether a cell

contains a value that can be evaluated as a number. For instance, if cell A1 contains the data 123

(even if this cell is formatted as text), then the condition in:

If IsNumeric(Range("A1")) Then

will evaluate to True. On the other hand, if the cell contains the data 123 Main Street, then the

condition will evaluate to False.

7.4.2 The Immediate If Function

The Immediate If function has the syntax:

IIf(Expression, TruePart, FalsePart)

If Expression is True, then the function returns TruePart. If Expression is False, the

function returns FalsePart. For instance, the following code displays a dialog indicating

whether or not the first row in the active worksheet is empty:

Dim rng As Range

Set rng = ActiveSheet.Rows(1)

MsgBox IIf(IsEmpty(ActiveSheet.Cells(1, 1)), _

"Cell is empty", "Cell is not empty")

It is very important to note that the Immediate If function always evaluates both TruePart and

FalsePart, even though it returns only one of them. Hence, we must be careful about

undesirable side effects. For example, the following code will produce a division by zero error

because even though the IIf function returns 1/x only when x is not equal to 0, the expression

1/x is evaluated in all cases, including when x is equal to 0:

x = 0

y = IIf(x = 0, x ^ 2, 1 / x)

7.4.3 The Switch Function

The syntax of the Switch function is:

Switch(expr1, value1, expr2, value2, ... , exprn, valuen)

where exprn and valuen are expressions. Note that there need only be one expression-value

pair, but the function is more meaningful if there are at least two such pairs.

The Switch function evaluates each expression exprn. When it encounters the first True

expression, it returns the corresponding value. As with the IIf function, Switch always

evaluates all of the expressions. If none of the expressions is True, the function returns Null. This

can be tested with the IsNull function.

The procedure in Example 7-1 displays the type of file based on its extension: Template,

Workbook, or Add-in.

Example 7-1. The Switch Function

Sub ShowFileType(FileExt As String)

Dim FileType As Variant


FileType = Switch(FileExt = "xlt", "Template", _

FileExt = "xls", "Workbook", _

FileExt = "xla", "Addin")

' Display result

If Not IsNull(FileType) Then

MsgBox FileType


MsgBox "Unrecognized type"

End If

End Sub

There is one subtlety in this code. Since the Switch function can return a Null value, we cannot

assign the return value to a String variable, as we might first try to do:

Dim FileType As String

FileType = Switch(FileExt = "xlt", "Template", _

FileExt = "xls", "Workbook", _

FileExt = "xla", "Addin")

This will not produce an error unless FileExt is not "xlt," "xls," or "xla," in which case we will

get the very annoying error message, "Invalid use of Null." The solution is to declare FileType

as a Variant, which can hold any data type, including no data type, which is indicated by the Null

keyword. (This issue can also be avoided by using a Select Case statement, discussed in

Chapter 8.)

7.4.4 Units Conversions

The InchesToPoints function converts a measurement given in inches to one given in points.

The reason this is important is that many Excel values need to be given (or are returned) in points,

but most of us prefer to think in inches (there are 72 points in one inch).

This applies especially to positioning properties, such as Top and Left. For instance, the Top

property of a ChartObject specifies the location of the top of the chart object, measured in points,

from Row 1 of the worksheet. Thus, to set this value to .25 inches, we would write:

ActiveChart.ChartObject.Top = InchesToPoints(.25)

There is also a PointsToInches function that is useful for displaying the return value of a

function in inches when the function returns the value in points.

7.4.5 The Beep Statement

This simple statement, whose syntax is:


sounds a single tone through the computer's speakers. It can be useful (when used with restraint) if

we want to get the user's attention. However, there is a caveat: the results are dependent upon the

computer's hardware and so the statement may not produce a sound at all! Thus, if you use this

statement in your code, be sure to warn the user. (It is possible, and probably better in general, to

use the Excel status bar to display messages to the user that do not interfere with execution of a

program. This is done using the StatusBar property of the Application object.)


7.5 Handling Errors in Code

We discussed the various types of errors in Chapter 3, but we have scrupulously avoided the

question of how to handle run-time errors in code. Indeed, VBA provides several tools for

handling errors (On Error, Resume, the Err object, and so on), and we could include an entire

chapter on the subject in this book.

Proper error handling is extremely important. Indeed, if you are, or intend to become, a

professional application developer, you should familiarize yourself with error-handling procedures.

On the other hand, if your intention is to produce Excel VBA code for your own personal use, the

reasons for adding error-handling routines are somewhat mitigated. When an error occurs within

one of your own programs, VBA will stop execution, display an error message, and highlight the

offending code. This should enable you to debug the application and fix the problem. (It would be

unreasonable to expect another user of your program to debug your code, however.)

Let us undertake a brief discussion of the highlights of error handling. (For more details, may I

suggest my book Concepts of Object-Oriented Programming in Visual Basic, published by

Springer-Verlag. It has a detailed chapter on error handling.)




7.5.1 The On Error Goto Label Statement

The On Error statement tells VBA what to do when a run-time error occurs. The most common

form of the statement is:

On Error GoTo label


where label is a label. For instance, consider the following code:

Sub example()


MsgBox Selection.Cells.Count

Exit Sub


MsgBox Err.Description, vbCritical

Exit Sub

End Sub

The purpose of this procedure is simply to display the number of cells in the current selection.

When the current selection is a worksheet range, the Cells property returns the collection of cells

in the selection and the Count property then returns the number of cells.

However, if the current selection is not a worksheet range (it might be a drawing object or a chart,

for instance), then the Cells property fails. To deal with this possibility in a friendly manner, we

add some error checking. The line:


tells VBA to move execution to the label ERR_EXAMPLE if an error occurs. The code following

this label is called the error-handling code. If an error should occur, the next line executed is the

77 ®


MsgBox line, in which case the dialog in Figure 7-3 will be displayed. This message gives a

description of the error, obtained from the Error object, which we discuss in the next section.

Figure 7-3. An error dialog

It is important to note the line just before the ERR_EXAMPLE label:

Exit Sub

Without this statement, the error-handling code will always be executed, even when there is no

error! Omitting this line is a common mistake. Note also that labels always end with a colon.

7.5.2 The Error Object

The error object, Err object, belongs to the VBA object model. The most important properties of

this object are:


The VBA error number


The name of the current VBA project


A description of the error

Note that the Clear method of the Err object will clear all of the properties of the Err object,

setting its Number property to 0 (which indicates the absence of an error).

7.5.3 The On Error GoTo 0 Statement

The statement:

On Error GoTo 0

turns off any previous On Error GoTo label statements. Any error occurring subsequently will

be handled by VBA in its own inimitable way.

7.5.4 The On Error Resume Next Statement

The syntax:


On Error Resume Next

tells VBA to continue executing the code immediately following the line that caused the error.

There are two important uses for this form of On Error. The first is to cause VBA to ignore an

error. For instance, the code:

Sub example()

On Error Resume Next

MsgBox Selection.Cells.Count

End Sub

will report the cell count when the selection is a worksheet range and do nothing when the

selection is not a worksheet range.

Another important use for the On Error Resume Next syntax is for in-line error checking,

where we check for errors immediately following the line that may have caused an error. For

instance, another way to handle errors in the previous example is:

Sub example()

On Error Resume Next

MsgBox Selection.Cells.Count

If Err.Number <> 0 Then

MsgBox Err.Description, vbCritical

End If

End Sub

7.5.5 The Resume Statement

It is also possible to include the Resume statement in the error-handling portion of the code. This

will cause VBA to resume execution at the line that follows the one that caused the error. Thus,

the previous code is equivalent to the following:

Sub example()


MsgBox Selection.Cells.Count

Exit Sub


MsgBox Err.Description, vbCritical

Resume Next

End Sub

There are three variations on the Resume statement:


Resume Next

Resume ALabel

The first version will cause VBA to resume with the line that caused the error. This is useful if

your error-handling code actually repairs the error condition and you want the line that caused the

original error to be executed again.

To illustrate, the procedure in Example 7-2 is designed to open a workbook named a:\test.xls. If it

does not exist, an error will occur. The error-handling code gives the user a chance to enter a new

workbook name, in which case we want to execute the Open method again. Hence the use of the

Resume statement.


Example 7-2. Error Handling with the Resume Statement

Sub test()

Dim sNew As String

sNew = "a:\test.xls"

On Error GoTo ERR_DISK

Workbooks.Open sNew

Exit Sub


If Err.Number = 1004 Then

sNew = InputBox("Cannot find file. Enter new location or

leave blank to

If sNew <> "" Then



Exit Sub

End If

End If

End Sub

The third variation:

Resume ALabel

causes VBA to resume execution at the line labeled ALabel.


Chapter 8. Control Statements

We conclude our discussion of the VBA language with a discussion of the main VBA control

statements, which are statements that affect the flow of control (or flow of execution) in a program.

8.1 The If...Then Statement

The If...Then statement is used for conditional control. The syntax is:

If Condition Then

' statements go here

ElseIf AnotherCondition

' more statements go


' more statements go

End If

. . .


here . . .

here . . .

Note that we may include more than one

ElseIf part and that both the ElseIf part(s) and the Else part are optional. We can also

squeeze all parts of this statement onto a single line, which is generally only a good idea when the

ElseIf and Else parts are missing. As an example, the following code deletes the current

selection in the active worksheet if it contains more than one cell:

If Selection.Count > 1 Then Selection.Delete

The following example changes the color of the current selection based upon its location—

selected cells in odd-numbered rows are colored red, those in even-numbered rows are colored


Dim oCell As Range

For Each oCell In Selection.Cells

If (oCell.Row Mod 2) = 1 Then

' odd

oCell.Interior.ColorIndex = 3


' even

oCell.Interior.ColorIndex = 5

End If


' red

' blue

8.2 The For Loop

The For...Next statement provides a method for repeatedly looping through a block of code

(that is, one or more lines of code). This loop is naturally referred to as a For loop. The basic

syntax is:

For counter = start To end

' block of code goes here . . .


Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Figure 7-2. An InputBox dialog box

Tải bản đầy đủ ngay(0 tr)