This blog shows the various techniques within Excel Visual Basic for moving around and selecting cells relative to the active cell or selection. The blog includes a discussion of the Offset, End, Resize, Range, EntireRow, EntireColumn and CurrentRegion methods.
- Selecting Cells with Excel VBA Macros - Relative
- Moving Around a Spreadsheet in VBA - Offset (this blog)
- Selecting to the End of a Block in Excel VBA macros
- Selecting a Block of Cells using Range
- Resizing Blocks of Cells in Excel VBA macros
- Selecting Entire Columns or Rows in Excel VBA macros
Posted by Andy Brown on 16 August 2011 | no comments
Moving Around a Spreadsheet in VBA - Offset
To move round a spreadsheet, use the Offset property. Let's suppose that you want to go from any character to their Poohsticks score in the example below:
With a character selected initially, you want to write a macro to select their score (ie the cell immediately to the right).
The Offset property which you need always specifies how many:
- rows down you need to go; and
- columns to the right you need to go.
In our case, we want to go 0 cells down and 1 column to the right:
All movement using Offset is down and to the right.
If you forget which order the directions come in, use autocompletion:
When you type in the Offset property, it's obvious that rows come before columns.
Thus the full command for our example would be:
'select a character's score
That is, take the current cell, move it 0 rows down and 1 column to the right, and select the result.
Moving Up and Left
If you've been reading thus far, you'll be wondering how you can possibly go up and to the left. The answer is to use negative numbers as the row and/or column offsets:
'given a character's score, select
'the character on their left
The macro above would go left one cell from the current one.
Overshooting the Edge of the Worksheet
If you try going too far in one direction, you'll generate an error. For example, suppose you're on the Winnie the Pooh cell and run this macro:
'assume that we have Winnie the Pooh selected (cell B5)
'and try to go up 100 rows
The result will be a less-than-friendly error message:
Microsoft politely telling you that you've gone beyond the edge of a worksheet
The Most Common Errors using Offset
The most common mistake using Offset is to forget to select the results of an offset (in the code below, we need to add .Select to the end of the command in CAPITALS, to complete the sentence):
'given a character, select their score (ie go right one cell)
The other common mistake is to get the row and column offsets the wrong way round!
Now that we've learnt how to move around a worksheet, let's look at something slightly more complicated: ie going to the end of a block of cells.