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.

Chapter 24: VBA Programming Concepts 653<br />

When you use For-Next loops, you should understand that the loop counter is a normal<br />

variable — it is not a special type of variable. As a result, you can change the value<br />

of the loop counter within the block of code executed between the For and Next<br />

statements. this is, however, a very bad practice and can cause problems. In fact, you<br />

should take special precautions to ensure that your code does not change the loop<br />

counter.<br />

You also can use a Step value to skip some values in the loop. Here’s the same function rewritten<br />

to sum every other integer between the first and last arguments:<br />

Function SumIntegers2(first, last)<br />

total = 0<br />

For num = first To last Step 2<br />

total = total + num<br />

Next num<br />

SumIntegers2 = Total<br />

End Function<br />

The following formula returns 25, which is the sum of 1, 3, 5, 7, and 9:<br />

=SumIntegers2(1,10)<br />

For-Next loops can also include one or more Exit For statements within the loop. When<br />

this statement is encountered, the loop terminates immediately, as the following example<br />

demonstrates:<br />

Function RowOfLargest(c)<br />

NumRows = Rows.Count<br />

MaxVal = WorksheetFunction.Max(Columns(c))<br />

For r = 1 To NumRows<br />

If Cells(r, c) = MaxVal Then<br />

RowOfLargest = r<br />

Exit For<br />

End If<br />

Next r<br />

End Function<br />

The RowOfLargest function accepts a column number (1–16,384) for its argument and returns the<br />

row number of the largest value in that column. It starts by getting a count of the number of rows<br />

in the worksheet. (This varies, depending on the version of Excel.) This number is assigned to the<br />

NumRows variable. The maximum value in the column is calculated by using the Excel MAX function,<br />

and this value is assigned to the MaxVal variable.

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

Saved successfully!

Ooh no, something went wrong!