Thursday, September 22, 2005

Turtle Graphics in Excel?

Surely we can't draw in Excel like we did with our Turtle Graphics?? Well, not exactly... but we can learn how to use a useful Excel object, called the "ActiveCell" ,while trying to draw in our Excel worksheet!

So far we've been using the Cells(row,col) method to interact with our spreadsheet. For example:

Cells(5,3) = txtFirstName

But there are other ways that we can interact with the spreadsheet from VBA. It's often handy to know a different way to do something, because it might make your job easier in a different situation! Instead of the Cells() method, we can also use the Range method as follows:

Sub Test()
Worksheets("Sheet1").Activate
Worksheets("Sheet1").Range("A5").Activate
End Sub

The above code activates Sheet1 and then activates the cell "A5" on sheet 1. One obvious benefit to this Range Method is that it uses the more familiar "A5" notation that we're used to. This is great if we know the exace cell (or named range) that we want to use... but can you think of a situation where the Range method won't work?

One really useful way to interact with the Worksheet is to use the ActiveCell property - it simply refers to whichever cell is currently activated (ie. the cell that currently has the black border around it - usually this is the last cell that you clicked!)

We can set some of the properties of the ActiveCell, such as its colour:

ActiveCell.Interior.ColorIndex = 5

Or, we can move the active cell by offsetting across or down the page:

ActiveCell.Offset(0, 1).Activate

For example, copy and paste the following sub into your vba_functions.xls file:
Sub DrawLine()
ActiveCell.Interior.ColorIndex = 5
ActiveCell.Offset(0, 1).Activate
End Sub

What happens when you run this sub? And when you run it again? And again?

Exercises:
  1. Modify the DrawLine sub so that it draws a line down the worksheet, rather than across.
  2. Modify the DrawLine sub so that, instead of only drawing one cell each time it is run, it draws a line using 3 cells.
  3. Create a new Sub called DrawSquare, that uses the ActiveCell property to change the colour of a cell, before moving on to the next cell... eventually drawing a 5x5 square.
  4. Create a new Sub called DrawDiamond, that does exactly that!
  5. (Tricky) Create a new Sub called DrawHouse and see what you can come up with!
Now you're ready to tackle Band Scenario 6!

1 Comments:

Anonymous Anonymous said...

On Microsoft.com, Ain't Life Weird?
Robert Scoble | Contributing Writer | 2005-09-21 OK, this is a little much. I'm on the home page of Microsoft.com right now.
Hi, I was just blog surfing and found you! If you are interested, go see my Business opportunity related site. It is special to me plus you may find something of interest.This has a great business opportunity as well

8:31 PM

 

Post a Comment

<< Home