Thursday, April 06, 2006

Getting started with Looping!

It's time for us to start learning how to do while-loops! (That is, to repeat some bit of code while something is true). To get started, create a new workbook called "looping.xls" and create the following subroutine:

Option Explicit

Sub Counting()
'We're going to make up a variable to count through our while-loop:

Dim count as Integer
count = 0

While count < 10
MsgBox("Count =" & count)
count = count + 1
Wend
End Sub
Now add a button to your worksheet "Start Counting" and link it to your new macro. Run your code by clicking on your button and make sure it does what you expect it to do! Step through the code to watch what it does. Now, have a go at the following:
  1. Call your second button "Even Numbers" and see if you can add a similar function that only counts even numbers (Hint: start with the exact code above).
  2. Modify your EvenNumbers so that it counts "Odd Numbers" from 1 to 9 instead.
  3. Modify your sub so that it count numbers up to 5 only. Check that they work correctly.
  4. Modify your sub so that it counts the odd numbers between 90 and 100.
Add another Sub routine as follows:


Sub CountingCells()
'We're going to make up a variable to count through our while-loop:
Dim count as Integer
count = 0
Range("A1").Select

While count < 10
ActiveCell.Value = count

'Now increment our counter, and move the active cell one down
count = count + 1
ActiveCell.Offset(1,0).Select
Wend
End Sub

Step through and watch your code to see what it does! Then,

  1. Modify your sub so that the numbers go across the page instead of down the page.
  2. Modify your sub so that the numbers go diagonally down the page.
  3. Modify your sub so that it goes down the page again (back to the original), but only uses every second row.
  4. Modify your sub so that, instead of entering a number in the cell, your sub sets the colour of every second cell (When you've got lots of information in a worksheet, it's sometimes really helpful to use an off-white (or pastel) colour for every second row - it helps to differentiate the rows of information). You'll probably need to record a macro to find some of the code to change the color of a cell
  5. Ensure that your sub does all the cells up to the 100th row.
  6. Using the ActiveCell object, see if you can find a property corresponding to the entire row (do ActiveCell. and see what pops up). Use this to modify your subroutine to set the colour of the entire row.
Remember, the power of loops is that you can repeat any simple action as many times as you want!