Monday, August 13, 2007

Sorry to be an excel bore, but when I was looking for the answer to this connundrum, I saw many people asking but very few clear answers. Every person new to Excel Macros must be annoyed that when recording the 'copy down' function to copy a formula down Excel records the absolute values, not the relative values. i.e. it will record that you selected B1:B20 rather than the adjacent cells to A1:A20, which is what you wanted. Here is the VBA code to do this:

Sub SelectAdjColumn()
Dim UpBound As Range
Dim LowBound As Range

If ActiveCell.Row > 1 Then
If IsEmpty(ActiveCell.Offset(-1, 0)) Then
Set UpBound = ActiveCell.Offset(0, 0)
Else
Set UpBound = ActiveCell.End(xlUp).Offset(0, 0)
End If
Else
Set UpBound = ActiveCell.Offset(0, 0)
End If

If ActiveCell.Row < Rows.Count Then
If IsEmpty(ActiveCell.Offset(1, 0)) Then
Set LowBound = ActiveCell.Offset(0, 0)
Else
Set LowBound = ActiveCell.End(xlDown).Offset(0, 0)
End If
Else
Set LowBound = ActiveCell.Offset(0, 0)
End If

Range(UpBound.Offset(0, 1), LowBound.Offset(0, 1)).Select

Set UpBound = Nothing
Set LowBound = Nothing
End Sub

Basically what this is doing is finding the top and bottom of the used range (in the same column as the currently active cell), and then selecting the adjacent cells. By adding your copy and paste arguments before and after this it will 'copy down' the formula. I have left all the offset(0, 0) in as by changing these you can pretty much make it select any cells in the sheet you could ever want.

0 Comments:

Post a Comment

<< Home