How to select range in Excel ListColumn's DataBodyRange from second to second last cell with VBA

4.6k Views Asked by At

I have data formatted as a table. I am trying to choose a range of cells in a certain column, regardless of the cells having data. The number of rows in the table will change, which is why I need to use a dynamic range.

I managed to select the entire data body range of the table column, in addition to a range from the second cell to the last.

I plan to apply a conditional formatting macro to the range if I can set the range.

I struggle with getting a range down until the second last cell in the table column.

Sub SelectRange()

Dim LC As ListColumn
Dim SecondCell As Long
Dim LastCell As Long
Dim SecondtoLastCell As Long

Set LC = Worksheets("On-going").ListObjects("Table4").ListColumns("Redos (no.)")
    'Choosing the table column with the header "Redos (no.)", works like a charm

With LC
    SecondCell = .DataBodyRange(2)
        'Choosing the second cell of the column, no problem
    
    SecondtoLastCell = .Range(.DataBodyRange.Rows.Count)
        'Choosing the second to last cell of the column. Came by this accidentally while trying everything, I have no idea why it works.

    '~~~Insert Range.Here
    'THE PROBLEM IS CREATING A RANGE FROM SecondCell TO SecondtoLastCell
 
End With

End Sub

I feel I have tried every possibility, including Range(SecondCell & SecondtoLastCell).Select and Range(SecondCell, Range(SecondtoLastCell)).Select. All that usually happens is that one cell above the column header row ("Redos (no.)" is selected.

2

There are 2 best solutions below

0
On BEST ANSWER

One option is to use Range.Resize here:

Set LC = Worksheets("On-going").ListObjects("Table4").ListColumns("Redos (no.)")

With LC.DataBodyRange
    Dim myRange As Range
    Set myRange = .Cells(2).Resize(.Rows.Count - 2)
End With
1
On

Thank you @BigBen! Such an elegant solution.

I got the range spot on with Set myRange = .Cells(2).Resize(.Rows.Count - 2).