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.

Part VI<br />

Programming Excel with VBA<br />

ON the CD-ROM<br />

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

named select cells.xlsm.<br />

Selecting a row or column<br />

The macro that follows demonstrates how to select the column of the active cell. It uses the<br />

EntireColumn property, which returns a range that consists of a column.<br />

Sub SelectColumn()<br />

ActiveCell.EntireColumn.Select<br />

End Sub<br />

As you may suspect, an EntireRow property also is available, which returns a range that consists of a row.<br />

If you want to perform an operation on all cells in the selected column, you don’t need to select the column.<br />

For example, when the following procedure is executed, all cells in the row that contains the active cell are<br />

made bold:<br />

Sub MakeRowBold()<br />

ActiveCell.EntireRow.Font.Bold = True<br />

End Sub<br />

Moving a range<br />

Moving a range consists of cutting it to the Clipboard and then pasting it to another area. If you record your<br />

actions while performing a move operation, the macro recorder generates code as follows:<br />

Sub MoveRange()<br />

Range(“A1:C6”).Select<br />

Selection.Cut<br />

Range(“A10”).Select<br />

ActiveSheet.Paste<br />

End Sub<br />

As demonstrated with copying earlier in this chapter (see “Copying a range”), this method is not the most<br />

efficient way to move a range of cells. In fact, you can do it with a single VBA statement, as follows:<br />

Sub MoveRange2()<br />

Range(“A1:C6”).Cut Range(“A10”)<br />

End Sub<br />

This statement takes advantage of the fact that the Cut method can use an argument that specifies the<br />

destination.<br />

ON the CD-ROM<br />

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

named range move.xlsm.<br />

Looping through a range efficiently<br />

Many macros perform an operation on each cell in a range, or they may perform selective actions based on<br />

the content of each cell. These operations usually involve a For-Next loop that processes each cell in the<br />

range.<br />

760

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

Saved successfully!

Ooh no, something went wrong!