简体   繁体   English

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

[英]Excel VBA: find the last empty cell in an Excel table, not range

I found that the following code doesn't return the last used row number in that particular column. 我发现以下代码不会返回该特定列中最后使用的行号。

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

What it returns is the last used row number in the Excel table. 它返回的是Excel表中最后使用的行号。

I have an Excel table with the range A1:AB142. 我有一个范围为A1:AB142的Excel表。 In the last row (142), only column B has data, the rest being empty. 在最后一行(142)中,只有列B具有数据,其余为空。 The above code returns 142, not 141, no matter what the last_data_column is (I tried 22, and 23). 无论last_data_column是什么,上面的代码都返回142,而不是141(我尝试过22和23)。

Similarly,End(xlDown) doesn't work properly. 同样,End(xlDown)不能正常工作。 Even though only W1 has data and the rest of the first row is blank, 即使只有W1有数据,而第一行的其余部分为空白,

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

gives 2, when W142 is blank and W1 to W141 are not blank. 当W142为空白且W1至W141不为空时,给出2。

How to find the last empty cell in a particular column in an Excel table?, 如何在Excel表格的特定列中查找最后一个空单元格?,

Use the .Find method to find the last row with data in your table. 使用.Find方法查找表中数据的最后一行。

Then offset by one to fine the last empty row. 然后偏移一以精简最后一个空行。

Something like (to get the last row): 类似于(获取最后一行)的内容:

    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

To find the First empty row, something like: 要找到第一个空行,类似于:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM