235
Learning Tricks of the Trade
Writing Code to Handle Any Size Data Range
The macro recorder hard-codes the fact that your data is in a range, such as A1:K415501.
Although this hard-coding works for today’s dataset, it may not work as you get new
datasets. You need to write code that can deal with different size datasets.
The macro recorder uses syntax such as
Range(“H12”)
to refer to a cell. However, it is more
flexible to use
Cells(12, 8)
to refer to the cell in row 12, column 8. Similarly, the macro
recorder refers to a rectangular range as
Range(“A1:K415501”)
. However, it is more flexible to
use the
Cells
syntax to refer to the upper-left corner of the range and then use the
Resize()
syntax to refer to the number of rows and columns in the range. The equivalent way to
describe the preceding range is
Cells(1, 1).Resize(415501,11)
. This approach is more
flexible because you can replace any of the numbers with a variable.
In the Excel user interface, you can use the End key on the keyboard to jump to the end of a
range of data. If you move the cell pointer to the final row on the worksheet and press the
End key followed by the up-arrow key, the cell pointer jumps to the last row with data. The
equivalent of doing this in VBA is to use the following code:
Range(“A1048576”).End(xlUp).Select
You don’t need to select this cell; you just need to find the row number that contains the last
row. The following code locates this row and saves the row number to a variable named
FinalRow
:
FinalRow = Range(“A1048576”).End(xlUp).Row
There is nothing magic about the variable name
FinalRow
. You could call this variable
x
or
y
, or even your dog’s name. However, because VBA allows you to use meaningful variable
names, you should use something such as
FinalRow
to describe the final row.
11
Excel 2007 offers 1,048,576 rows and 16,384 columns. Excel 97 through Excel 2003 offered 65,536
rows and 256 columns.To make your code flexible enough to handle any versions of Excel, you can
use
Rows.Count
to learn the total number of rows in this version of Excel.The preceding code
could then be generalized like so:
FinalRow = Cells(Rows.Count, 1).End(xlUp).Row
NO
TE
You also can find the final column in a dataset. If you are relatively sure that the dataset
begins in row 1, you can use the End key in combination with the left-arrow key to jump
from cell XFD1 to the last column with data. To generalize for the possibility that the code
is running in earlier versions of Excel, you can use the following code:
FinalCol = Cells(1, Columns.Count).End(xlToLeft).Column
12_0789736012_CH11.qxd 12/11/06 6:26 PM Page 235
Содержание VBA
Страница 60: ......