excel - 查找仅包含最后一行的第一个单元格的范围?
问题描述
我需要计算一个只包含一个单元格的范围。此单元格来自最后一行和第一列。如果工作表为空,则范围为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
这该怎么做?
解决方案
如果我理解正确,您希望在某个范围(或一堆列)中找到最后一行。
实现此目的的一种方法可能是遍历范围内的每一列,找到最后一个单元格(在该特定列中)的行,并检查它是否超过了循环中迄今为止最大的最后一行。
在下面的代码中,如果您更改"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
推荐阅读
- c++ - 有没有办法通过 zeromq pub sub C++ 发送字符串以外的数据类型?
- bootstrap-4 - bootstrap 手风琴中只有第一个项目正在崩溃 - z-index 问题
- angular - Crud 到 ASP.NET Core 时找不到处理程序引用的静态文件
- python - 在numpy数组中使用给定元素创建箱线图的问题
- python - 只能将 .dt 访问器与 datetimelike 值一起使用
- html - 使用 Flexbox 在一个部分周围放置两个侧边块
- python - TensorFlow/Keras:如何从我的广义骰子损失函数中获得有意义的损失值?
- javascript - 当我尝试创建 antd 自定义表单时,Typescript 构建失败
- python - Python WordCloud 代码中的导入错误。他们说没有名为 wordcloud 的模块
- sql - 减少查询执行时间