Excel VBA:在Excel表中查找最后一个空单元格,而不是范围

时间:2019-08-18 05:17:46

标签: excel vba

我发现以下代码没有返回该特定列中最后使用的行号。

ThisWorkbook.Sheets(1).Cells(max_row, last_data_column + 1).End(xlUp).Row

返回的是Excel表中最后使用的行号。

我有一个范围为A1:AB142的Excel表。在最后一行(142)中,只有列B具有数据,其余为空。不管last_data_column是什么,上面的代码都返回142,而不是141(我尝试过22和23)。

类似地,End(xlDown)不能正常工作。即使只有W1有数据,而第一行的其余部分为空白,

ThisWorkbook.Sheets(1).Range("W1").End(xlDown).Row

给出2,当W142为空白而W1至W141不为空白时。

如何在Excel表格的特定列中查找最后一个空单元格?,

1 个答案:

答案 0 :(得分:0)

使用.Find方法在表中查找包含数据的最后一行。

然后再偏移一以对最后个空行进行罚款。

类似的东西(获取最后一行):

    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

要找到 First 空行,例如:

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