Tuesday, September 22, 2015

Range and Offset

We have learned how Range object works. Offset method can be used for the object to move the range to somewhere else.

For example, we consider of selecting a range A1 at first.

Sub TestSub()

Range("A1").Select

End Sub

This Sub selects the A1 cell. Then we move this cell to E5 using Offset method.

Sub TestSub()

Range("A1").Offset(4,4).Select

End Sub

We run the macro and see what happens. Running this code, can you see that the selecting on the A1 cell moved to E5 cell? (Maybe it would be easier to do this by making a button for this macro)

This is the offset. You can move the location of the cell which you are selecting. Not only a single cell, you can designate multiple cells to move with the Offset method.

Sub TestSub()

Range("A1:D5").Offset(4,1).Select

End Sub

This macro moves the location of the range from (A1:D5) to (B5:E9) because it moves like (A+1 1+4:D+1:5+4).

You can use also negative numbers like this.

Sub TestSub()

Range("E7").Offset(-4,-3).Select

End Sub

This would move to B3 cell.