excel - Excel VBA:查找Excel表格中的最后一个空单元格,而不是范围
问题描述
我发现以下代码不会返回该特定列中最后使用的行号。
ThisWorkbook.Sheets(1).Cells(max_row, last_data_column + 1).End(xlUp).Row
它返回的是 Excel 表中最后使用的行号。
我有一个范围为 A1:AB142 的 Excel 表。在最后一行 (142) 中,只有 B 列有数据,其余为空。上面的代码返回 142,而不是 141,不管 last_data_column 是什么(我试过 22 和 23)。
同样,End(xlDown) 也不能正常工作。即使只有 W1 有数据并且第一行的其余部分是空白的,
ThisWorkbook.Sheets(1).Range("W1").End(xlDown).Row
给出 2,当 W142 为空白且 W1 到 W141 不为空白时。
如何在 Excel 表格的特定列中找到最后一个空单元格?
解决方案
使用该.Find
方法查找表中包含数据的最后一行。
然后偏移 1 以细化最后一个空行。
像(得到最后一行):
Dim LO As ListObject
Dim C As Range
Set LO = Sheet1.ListObjects("Table1")
With LO.Range.Columns(column_to_check) 'column_to_check is relative to the LO.Range
Set C = .Find(what:="*", after:=.Cells(1), LookIn:=xlValues, _
searchorder:=xlByRows, searchdirection:=xlPrevious)
If Not C Is Nothing Then
'do stuff`
Debug.Print C.Row+1 'last empty row
'If the row is the last in the table, then column is full
End If
要查找第一个空行,例如:
With LO.Range.Columns(1)
Set C = .Find(what:="", after:=.Cells(1), LookIn:=xlValues, _
searchorder:=xlByRows, searchdirection:=xlNext)
If Not C Is Nothing Then
'do stuff`
Debug.Print C.Row 'First empty row
End If
End With
推荐阅读
- asp.net-core - 部署 Asp.net Core 3.1 在 Windows 服务器上不起作用
- react-native - 使用 react hooks 调度后获取更新的 redux 状态
- r - 将 table() 结果迭代到矩阵/数据框中
- python - 在 sql alchemy 中转义表名
- flutter - AppBar 未显示在脚手架中
- javascript - 单击时更改按钮颜色
- gradle - 如何从 intellij 项目中删除 gradle 支持?
- c# - 获取每个文件的文件位置到一个流中
- python - Google colab 在使用 tensorflow 2.0 批处理数据集时未加载图像文件
- java - Spring boot data.sql 不会在 Postgresql 中初始化数据