11.08.2013 Views

Excel's Formula - sisman

Excel's Formula - sisman

Excel's Formula - sisman

SHOW MORE
SHOW LESS

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

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

700<br />

Part VI: Developing Custom Worksheet Functions<br />

If Wksht.Range(Addr) > MaxVal Then _<br />

MaxVal = Wksht.Range(Addr).Value<br />

End If<br />

End If<br />

Next Wksht<br />

If MaxVal = –9.9E+307 Then MaxVal = CVErr(xlErrValue)<br />

MAXALLSHEETS = MaxVal<br />

End Function<br />

The For Each statement uses the following expression to access the workbook:<br />

cell.Parent.Parent.Worksheets<br />

The parent of the cell is a worksheet, and the parent of the worksheet is the workbook. Therefore,<br />

the For Each-Next loop cycles among all worksheets in the workbook. The first If statement<br />

inside the loop checks whether the cell being checked is the cell that contains the function. If so,<br />

that cell is ignored to avoid a circular reference error.<br />

You can easily modify the MAXALLSHEETS function to perform other cross-worksheet<br />

calculations: Minimum, Average, Sum, and so on.<br />

The SHEETOFFSET function<br />

A recurring complaint about Excel (including Excel 2010) is its poor support for relative sheet<br />

references. For example, suppose that you have a multisheet workbook, and you enter a formula<br />

like the following on Sheet2:<br />

=Sheet1!A1+1<br />

This formula works fine. However, if you copy the formula to the next sheet (Sheet3), the formula<br />

continues to refer to Sheet1. Or if you insert a sheet between Sheet1 and Sheet2, the formula continues<br />

to refer to Sheet1, when most likely, you want it to refer to the newly inserted sheet. In<br />

fact, you can’t create formulas that refer to worksheets in a relative manner. However, you can<br />

use the SHEETOFFSET function to overcome this limitation.<br />

Following is a VBA Function procedure named SHEETOFFSET:<br />

Function SHEETOFFSET(Offset As Long, Optional cell As Variant)<br />

‘ Returns cell contents at Ref, in sheet offset<br />

Dim WksIndex As Long, WksNum As Long<br />

Dim wks As Worksheet<br />

Application.Volatile<br />

If IsMissing(cell) Then Set cell = Application.Caller

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

Saved successfully!

Ooh no, something went wrong!