首页 > 解决方案 > 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 表格的特定列中找到最后一个空单元格?

标签: excelvba

解决方案


使用该.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

推荐阅读