简体   繁体   English

如何使用VBA在Excel ListColumn的DataBodyRange中从倒数第二个单元格中选择范围

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

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 .我觉得我已经尝试了所有的可能性,包括Range(SecondCell & SecondtoLastCell).SelectRange(SecondCell, Range(SecondtoLastCell)).Select All that usually happens is that one cell above the column header row ("Redos (no.)" is selected.通常发生的只是列标题行上方的一个单元格(“重做(编号)”)被选中。

One option is to use Range.Resize here:一种选择是在此处使用Range.Resize

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

Thank you @BigBen!谢谢@BigBen! Such an elegant solution.如此优雅的解决方案。

I got the range spot on with Set myRange = .Cells(2).Resize(.Rows.Count - 2) .我通过Set myRange = .Cells(2).Resize(.Rows.Count - 2)获得了范围点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM