如何将非连续Range调整至其最后非空列的最后单元格
调整非连续单元格区域至最后非空列的最后单元格
我有一个非连续单元格区域,例如"A2:B2,A4:B5,D2,D4:D5,F2:I2,F4:I5"。通过相关方法可以获取该区域的最后空单元格或非空单元格,现在需要将这个非连续区域调整到其最后非空列的最后单元格。
输入效果:
预期调整效果:
VBA实现代码
Sub Make_Selection1() Dim sh As Worksheet: Set sh = ActiveSheet Dim finalRange As Range Set finalRange = sh.Range("A2:B2,A4:B5,D2,D4:D5,F2:I2,F4:I5") getLastCell(finalRange).Select End Sub Function getLastCell(rg As Range, Optional fSelectNonEmptyCell As Boolean = True) As Range Dim c As Range, a As Range, maxColumn As Long, maxRow As Long For Each a In rg.Areas For Each c In a.Cells If (fSelectNonEmptyCell = True And LenB(c.Value) > 0) Or _ fSelectNonEmptyCell = False Then If c.Column > maxColumn Then maxColumn = c.Column If c.Row > maxRow Then maxRow = c.Row End If Next Next If maxRow > 0 And maxColumn > 0 Then Set getLastCell = rg.Parent.Cells(maxRow, maxColumn) Else If fSelectNonEmptyCell = True Then Err.Raise vbObjectError + 512, , "未在区域 " & rg.Address(, , , external:=True) & " 中找到非空单元格" Else Err.Raise vbObjectError + 512, , "未在区域 " & rg.Address(, , , external:=True) & " 中找到单元格" End If End If End Function
示例数据
| Title | Title | Title | Title | Title | Title | Title | Title | Title |
|---|---|---|---|---|---|---|---|---|
| 2 | 2 | 2 | 2 | 2 | 2 | |||
| 4 | 4 | 4 | 4 | 4 | 4 | 4 | ||
| 6 | 6 | 6 | 6 | 6 | 6 |
内容的提问来源于stack exchange,提问作者Peace
相关产品推荐
相关产品推荐

