18.11.2014 Views

Microsoft Office

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

VBA Examples 44<br />

FIGURE 44.1<br />

This range can consist of any number of rows.<br />

The macro that follows demonstrates how to copy this range from Sheet1 to Sheet2 (beginning at cell A1).<br />

It uses the CurrentRegion property, which returns a Range object that corresponds to the block of used<br />

cells surrounding a particular cell. This is equivalent to choosing Home ➪ Editing ➪ Find & Select ➪ Go<br />

To, clicking the Special button, and then selecting the Current Region option.<br />

ON the CD-ROM<br />

Sub CopyCurrentRegion()<br />

Range(“A1”).CurrentRegion.Copy Sheets(“Sheet2”).Range(“A1”)<br />

End Sub<br />

A workbook that contains this macro is available on the companion CD-ROM. The file is<br />

named range copy.xlsm.<br />

Selecting to the end of a row or column<br />

You probably are in the habit of using key combinations, such as pressing Ctrl+Shift+right-arrow key and<br />

Ctrl+Shift+down-arrow key, to select from the active cell to the end of a row or column. When you record<br />

these actions in Excel (using relative recording mode), you’ll find that the resulting code works as you<br />

would expect it to.<br />

The following VBA procedure selects the range that begins at the active cell and extends down to the last<br />

cell in the column (or to the first empty cell, whichever comes first). When the range is selected, you can do<br />

whatever you want with it — copy it, move it, format it, and so on.<br />

Sub SelectDown()<br />

Range(ActiveCell, ActiveCell.End(xlDown)).Select<br />

End Sub<br />

Notice that the Range property has two arguments. These arguments represent the upper-left and lowerright<br />

cells in a range.<br />

This example uses the End method of the Range object, which returns a Range object. The End method<br />

takes one argument, which can be any of the following constants: xlUp, xlDown, xlToLeft, or<br />

xlToRight.<br />

759

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!