Microsoft KB Archive/51063

{| = Excel: Optimizing the Speed of Macro Loops =
 * width="100%"|

Last reviewed: April 3, 1997

Article ID: Q51063 1.00 1.03 1.04 1.06 1.50 2.20 3.00 MACINTOSH kbother

SUMMARY
To improve macro speed in Microsoft Excel, you can use a cell as a counter along with a SET.VALUE command instead of a FOR/NEXT or WHILE/NEXT loop.

The following three macros are examples of implementing a loop counter. The first runs quite slowly, while the second and third run up to five times faster.

Slow Version for FOR/NEXT Loop with 10 Iterations -

A     1  =FOR(&quot;counter&quot;,1,10) 2 do something here 3 =NEXT 4 =RETURN

Fast Version (up to Five Times Faster) --

A     27  =SET.VALUE(A28,0) 28 =IF(A28=10,GOTO(A31),A28+1) 29 do something here 30 =GOTO(A28) 31 =RETURN

Alternative Fast Version

A     27  =SET.VALUE(A28,0) 28 =A28+1 29 do something here 30 =IF(A28<10,GOTO(A28)) 31 =RETURN In addition, move outside the loop any functions that need be calculated only once. Otherwise, time is taken by the function calculating each time through the loop.

MORE INFORMATION
This information was taken from the &quot;Macro Tips&quot; section on pages 153-154 in the &quot;Microsoft Excel Technical Reference for the Macintosh.&quot;

The &quot;Microsoft Excel Technical Reference for the Macintosh&quot; can be obtained as part of the Excel Developer's Kit. To obtain this kit, call Microsoft End User Sales and Service at (800) 426-9400.
 * }