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 />

With the larger worksheet size in Excel 2007, the Count property can generate an error.<br />

The Count property uses the Long data type, so the largest value that it can store is<br />

2,147,483,647. For example, if the user selects 2,048 complete columns (2,147,483,648 cells), the Count<br />

property generates an error. Fortunately, <strong>Microsoft</strong> added a new property: CountLarge. CountLarge uses<br />

the Double data type, which can handle values up to 1.79+E^308.<br />

Bottom line? In the vast majority of situations, the Count property will work fine. If there’s a chance that<br />

you may need to count more cells (such as all cells in a worksheet), use CountLarge instead of Count.<br />

CAUTION<br />

If the active sheet contains a range named data, the following statement assigns the number of cells in the<br />

data range to a variable named CellCount:<br />

CellCount = Range(“data”).Count<br />

You can also determine how many rows or columns are contained in a range. The following expression calculates<br />

the number of columns in the currently selected range:<br />

Selection.Columns.Count<br />

And, of course, you can also use the Rows property to determine the number of rows in a range. The following<br />

statement counts the number of rows in a range named data and assigns the number to a variable<br />

named RowCount:<br />

RowCount = Range(“data”).Rows.Count<br />

Working with Workbooks<br />

The examples in this section demonstrate various ways to use VBA to work with workbooks.<br />

Saving all workbooks<br />

The following procedure loops through all workbooks in the Workbooks collection and saves each file that<br />

has been saved previously:<br />

Public Sub SaveAllWorkbooks()<br />

Dim Book As Workbook<br />

For Each Book In Workbooks<br />

If Book.Path “” Then Book.Save<br />

Next Book<br />

End Sub<br />

Notice the use of the Path property. If a workbook’s Path property is empty, the file has never been saved<br />

(it’s a new workbook). This procedure ignores such workbooks and saves only the workbooks that have a<br />

nonempty Path property.<br />

Saving and closing all workbooks<br />

The following procedure loops through the Workbooks collection. The code saves and closes all workbooks.<br />

Sub CloseAllWorkbooks()<br />

Dim Book As Workbook<br />

For Each Book In Workbooks<br />

764

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

Saved successfully!

Ooh no, something went wrong!