Excel VBA设置Range后获取最后单元格结果不符合预期
解决Excel VBA中Range.Cells获取最后单元格不符合预期的问题
你的代码里用rg.Cells(rg.Cells.Count)想要拿到指定列表的最后一个单元格$K$2,但实际得到$B$8,核心原因是VBA对多单元格Range的Cells集合有固定排序逻辑:
VBA不会保留你输入单元格的顺序,而是会自动将所有单元格按「行优先(从上到下,每行内从左到右)」的规则重新排序,同时会把连续的单元格合并成一个区域(Area)。rg.Cells(rg.Cells.Count)取的是这个排序后的最后一个单元格,而非你输入顺序的最后一个。
解决方案
如果要获取你输入顺序的最后一个单元格(即$K$2),最可靠的方法是用数组存储单元格地址,直接取数组最后一项:
Sub GetLastCellInRange() Dim cellAddresses As Variant Dim lastCell As Range ' 将目标单元格地址存入数组 cellAddresses = Array("B3", "B4", "B5", "J2", "B6", "K2") ' 取数组最后一个元素对应的单元格 Set lastCell = Range(cellAddresses(UBound(cellAddresses))) MsgBox lastCell.Address End Sub
如果要获取整个Range中行列号最大的最右下角单元格,可以遍历所有单元格找出最大行和列:
Sub GetBottomRightCell() Dim rg As Range Dim maxRow As Long, maxCol As Long Dim cell As Range Set rg = Range("B3, B4, B5,J2, B6, K2") maxRow = 0 maxCol = 0 ' 遍历所有单元格,记录最大行号和列号 For Each cell In rg If cell.Row > maxRow Then maxRow = cell.Row If cell.Column > maxCol Then maxCol = cell.Column Next cell Set lastCell = Cells(maxRow, maxCol) MsgBox lastCell.Address ' 此示例中会返回$B$6(行号最大的单元格) End Sub
内容的提问来源于stack exchange,提问作者Vsn
相关产品推荐
相关产品推荐

