首页 > 解决方案 > 查找仅包含最后一行的第一个单元格的范围?

问题描述

我需要计算一个只包含一个单元格的范围。此单元格来自最后一行和第一列。如果工作表为空,则范围为A1:A1

我知道有很多方法可以计算最后一行,但我正在寻找一种优雅的方法来获取最后一行的第一个单元格。也许一些例子可以更好地解释。

示例 #1

 A B C D
1
2  X
3      X
4    X

结果#1

Range = A4:A4

示例 #2

 A B C D
1

结果#2

Range = A1:A1

这该怎么做?

标签: excelvba

解决方案


如果我理解正确,您希望在某个范围(或一堆列)中找到最后一行。

实现此目的的一种方法可能是遍历范围内的每一列,找到最后一个单元格(在该特定列中)的行,并检查它是否超过了循环中迄今为止最大的最后一行。

在下面的代码中,如果您更改"Sheet1"为您的工作表被调用的任何内容,并将范围从更改为"A4:Z5"类似"A:Z""A1:D4"(或您的情况下的任何内容),那么它应该显示您所追求的单元格的地址。

Option Explicit

Private Sub ShowLastCell()
    ' Change this to what your sheet is called.
    With ThisWorkbook.Worksheets("Sheet1")

        ' Change this to the range you need to check.
        With .Range("A4:Z5")
            Dim firstColumnToCheck As Long
            firstColumnToCheck = .Columns(1).Column

            Dim lastColumnToCheck As Long
            lastColumnToCheck = .Columns(.Columns.Count).Column
        End With

        Dim maxLastRow As Long
        Dim columnIndex As Long

        For columnIndex = firstColumnToCheck To lastColumnToCheck
            maxLastRow = Application.Max(maxLastRow, .Cells(.Rows.Count, columnIndex).End(xlUp).Row)
        Next columnIndex

        MsgBox ("I think the cell you want is " & .Cells(maxLastRow, "A").Address & ":" & .Cells(maxLastRow, "A").Address)

    End With
End Sub

推荐阅读