1. Trang chủ >
  2. Công Nghệ Thông Tin >
  3. Quản trị mạng >

Example 8-1. Finding the First Nonempty Cell

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (5.72 MB, 490 trang )

If Not IsEmpty(oCell) Then


bNone = False

Exit For

End If


If bNone Then MsgBox "No nonempty cells in row 1", vbInformation

End Sub

We can also control the step size and direction for the counter in a For loop using the Step

keyword. For instance, in the following code, the counter i is incremented by 2 each time the

block of code is executed:

For i = 1 to 10 Step 2

' code block goes here

Next i

The following loop counts down from 10 to 1 in increments of -1. This can be useful when we

want to examine a collection (such as the cells in a row or column) from the bottom up:

For i = 10 to 1 Step -1

' code block goes here

Next i

8.3 The For Each Loop

The For Each loop is a variation on the For loop that was designed to iterate through a

collection of objects (as well as through elements in an array) and is generally much more efficient

than using the traditional For loop. The general syntax is:

For ObjectVar In CollectionName

' block of code goes here . . .

Next ObjectVar

where ObjectVar is a variable of the same object type as the objects within the collection. The

code block will execute once for each object in the collection.

The FindFirstNonEmpty procedure shown in Example 8-1 illustrates the For Each loop.

Thus, when iterating through a collection of objects, we have two choices:

For Each object in Collection

' code block here

Next object


For i = 1 to Collection.Count

' code block here

Next i


It is important to keep in mind that the For Each loop can be much faster than the For loop when

dealing with collections of Excel objects. Thus, except for small collections, it is the preferred


8.4 The Do Loop

The Do loop has several variations. To describe these variations, we use the notation:

{While | Until}

to represent either the word While or the word Until, but not both. With this in mind, here are

the possible syntaxes for the Do loop:

Do {While | Until} condition

' code block here




' code block here

Loop {While | Until} condition

Actually, there is a fifth possibility, because we can dispense with condition completely and



' code block here


Some of these variations are actually quite subtle. For instance, the following code cycles through

the cells in the first row of the active worksheet as long as the cells are nonempty:

i = 1

Do While IsEmpty(ActiveSheet.Rows(1).Cells(i))

i = i + 1



(This code will cause some problems if the first row has no nonempty cells, but let's not worry

about that now.) Consider also the following code, whose purpose is similar:

i = 1


i = i + 1

Loop While Not IsEmpty(ActiveSheet.Rows(1).Cells(i))


The difference between these two versions is that, in the first case, the IsEmpty condition is

checked immediately, before any code within the Do loop is executed. Thus, if the first cell is

empty, the condition will fail, no code will be executed within the Do loop, and so this cell will be

selected (as it should be).


On the other hand, in the second case, the condition is checked at the end of each loop, so the loop

will execute the first time, even if the first cell is empty.

Just as the For loop has an Exit For statement for terminating the loop, a Do loop as an Exit

Do statement for exiting the Do loop.

8.5 The Select Case Statement

As we have seen, the If . . . Then . . . construct is used to perform different tasks based

on different possibilities. An alternative construct that is often more readable is the Select Case

statement, whose syntax is:

Select Case testexpression

Case value1

' statements to execute if testexpression = value1

Case value2

' statements to execute if testexpression = value2

. . .

Case Else

' statements to execute otherwise

End Select

Note that the Case Else part is optional. To illustrate, the following code is the Select Case

version of Example 7-1 in Chapter 7, (see the discussion of the Switch function) that displays the

type of a file based on its extension. I think you will agree that this is a bit more readable than the

previous version:

Sub ShowFileType(FileExt As String)

Dim FileType As Variant

Select Case FileExt

Case "xlt"

FileType = "Template"

Case "xls"

FileType = "Worksheet"

Case "xla", "utl"

FileType = "Addin"

Case Else

FileType = "unknown"

End Select

' Display result

MsgBox FileType

End Sub

Note the penultimate case statement:

Case "xla", "utl"

VBA allows us to place more than one condition in a case statement, separated by commas. This

is useful when more than one case produces the same result.


8.6 A Final Note on VBA

There is a lot more to the VBA language than we have covered here. In fact, the VBA reference

manual is about 300 pages long. However, we have covered the main points needed to begin Excel

VBA programming.[1]


If you'd like a good reference guide to the VBA language, see VB & VBA in a Nutshell: The Language,

written by Paul Lomax and published by O'Reilly & Associates.

Actually, many Excel VBA programming tasks require only a small portion of VBA's features and

you will probably find yourself wrestling much more with Excel's object model than with the

VBA language itself.

We conclude our discussion of the VBA language per se with a brief outline of topics for further

study, which you can do using the VBA help files.

8.6.1 File-Related Functions

VBA has a large number of functions related to file and directory housekeeping. Table 8-1

contains a selection of them.

Table 8-1. Some VBA File and Directory Functions




Find a file with a certain name.


Get the length of a file.


Get the date stamp of a file.


Copy a file.


Delete a file.


Rename a file or directory.


Delete a directory.


Make a new directory.

In addition to the file-related functions in Table 8-1, there may be times when it is useful to create

new text files to store data. VBA provides a number of functions for this purpose, headed by the

Open statement, whose (simplified) syntax is:

Open pathname For mode As [#]filenumber

Once a file has been opened, we can read or write to it.

8.6.2 Date- and Time-Related Functions

VBA has a large number of functions related to manipulating dates and times. Table 8-2 contains

a selection.

Table 8-2. Some Date- and Time-Related Functions



Date, Now, Time

Get the current date or time.


DateAdd, DateDiff, DatePart

DateSerial, DateValue

TimeSerial, TimeValue

Date, Time


Perform date calculations.

Return a date.

Return a time.

Set the date or time.

Time a process.

8.6.3 The Format Function

The Format function is used to format strings, numbers, and dates. Table 8-3 gives a few






Table 8-3. Format Function Examples


Return value

Format(Date, "Long Date")

Thursday, April 30, 1998

Format(Time, "Long Time")

5:03:47 PM

Format(Date, "mm/dd/yy hh:mm:ss AMPM")

04/30/98 12:00:00 AM

Format(1234.5, "$##,##0.00")


Format("HELLO", "<")


87 ®


Xem Thêm
Tải bản đầy đủ (.pdf) (490 trang)