从停产范围中提取第一个和最后一个单元格地址
Extract from Discontinues Range First and Last Cell Addres
有一个中断范围对象:
Range("$C:$C,$C0:$C000")
如何获取它的第一个和最后一个单元格?
firstCell = ("C1")<br>lastCell = ("C64000")
假设该范围内的任何单元格都可能是空白的,甚至是隐藏的?
我这边的首选方法是使用 属性 之类的 "last cell"、"first cell" 或类似的方法,并避免使用正则表达式或循环,但是否有类似的 属性?或获取此类信息的方法?
当您处理不连续的单元格时,您必须处理它们 Range.Areas property. By paring down the unioned range to the visible cells and non-blanks (e.g. constants) with the Range.SpecialCells method and xlCellTyp 您可以处理第一个或最后一个区域以获得您正在寻找的属性。
Sub main()
Dim firstCell As Range, lastCell As Range
Set firstCell = first_non_blank_visible_cell(Range("$C:$C,$C0:$C000"))
Set lastCell = last_non_blank_visible_cell(Range("$C:$C,$C0:$C000"))
Debug.Print firstCell.Address
Debug.Print lastCell.Address
End Sub
Function first_non_blank_visible_cell(rng As Range)
On Error Resume Next
Set rng = rng.SpecialCells(xlCellTypeVisible)
Set rng = rng.SpecialCells(xlCellTypeConstants)
With rng.Areas(1)
Set first_non_blank_visible_cell = .Cells(1)
End With
End Function
Function last_non_blank_visible_cell(rng As Range)
On Error Resume Next
Set rng = rng.SpecialCells(xlCellTypeVisible)
Set rng = rng.SpecialCells(xlCellTypeConstants)
With rng.Areas(rng.Areas.Count)
Set last_non_blank_visible_cell = .Cells(.Cells.Count)
End With
End Function
我一直在寻找 xlCellTypeConstants,因为您指定了非空白且公式不留空白;他们留下零长度的字符串。如果涉及公式,则可能需要进行一些小的修改以合并 xlCellTypeFormulas。
如果您的非连续范围包含 D8:X8 之类的内容,可能会有一些关于 X8 或 C64000 是否会被视为 'last cell' 的讨论,但您只引用了一个列,因此暂时没有意义。
有一个中断范围对象:
Range("$C:$C,$C0:$C000")
如何获取它的第一个和最后一个单元格?
firstCell = ("C1")<br>lastCell = ("C64000")
假设该范围内的任何单元格都可能是空白的,甚至是隐藏的?
我这边的首选方法是使用 属性 之类的 "last cell"、"first cell" 或类似的方法,并避免使用正则表达式或循环,但是否有类似的 属性?或获取此类信息的方法?
当您处理不连续的单元格时,您必须处理它们 Range.Areas property. By paring down the unioned range to the visible cells and non-blanks (e.g. constants) with the Range.SpecialCells method and xlCellTyp 您可以处理第一个或最后一个区域以获得您正在寻找的属性。
Sub main()
Dim firstCell As Range, lastCell As Range
Set firstCell = first_non_blank_visible_cell(Range("$C:$C,$C0:$C000"))
Set lastCell = last_non_blank_visible_cell(Range("$C:$C,$C0:$C000"))
Debug.Print firstCell.Address
Debug.Print lastCell.Address
End Sub
Function first_non_blank_visible_cell(rng As Range)
On Error Resume Next
Set rng = rng.SpecialCells(xlCellTypeVisible)
Set rng = rng.SpecialCells(xlCellTypeConstants)
With rng.Areas(1)
Set first_non_blank_visible_cell = .Cells(1)
End With
End Function
Function last_non_blank_visible_cell(rng As Range)
On Error Resume Next
Set rng = rng.SpecialCells(xlCellTypeVisible)
Set rng = rng.SpecialCells(xlCellTypeConstants)
With rng.Areas(rng.Areas.Count)
Set last_non_blank_visible_cell = .Cells(.Cells.Count)
End With
End Function
我一直在寻找 xlCellTypeConstants,因为您指定了非空白且公式不留空白;他们留下零长度的字符串。如果涉及公式,则可能需要进行一些小的修改以合并 xlCellTypeFormulas。
如果您的非连续范围包含 D8:X8 之类的内容,可能会有一些关于 X8 或 C64000 是否会被视为 'last cell' 的讨论,但您只引用了一个列,因此暂时没有意义。