Return table 列中的最后一个值

Return last value in table column

VBA 的新手。这两天一直在寻找答案,但没有找到真正问我想要答案的问题。

我正在使用在我的一张工作表中填充 Table 的用户窗体。

我的问题出在子 UserForm_Initialize() 中。我要做的第一件事就是找出我的 DataBodyRange 中的最后一行(顺便说一句,第一列)是否包含 table 包含 ID-number。

如果是,那么我取该值,加一,然后在我的用户窗体中填充一个文本框。

但是,如果 table 由 headers 和一个空行组成,我想用数字 1 填充文本框(通过另一个子项将添加到该空行) ,但我的代码因错误而停止工作。

使用以下代码我得到错误

Run-Time Error '91': Object Variable or With Block Variable Not Set

Private Sub UserForm_Initialize()
Dim tbl As ListObject, rng As Range

Set tbl = Worksheets("Sheet1").ListObjects("table1")
Set rng = tbl.ListColumns("ID").DataBodyRange

If IsEmpty(rng.Cells.Find("*", LookIn:=xlValues,_
           SearchOrder:=xlByRows,_
           SearchDirection:=xlPrevious).Value) Then
    Me.textBox.Value = 1
Else
    Me.textBox.Value = rng.Cells.Find("*", LookIn:=xlValues,_
           SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Value + 1
End If

End Sub

我不明白我找到的关于错误代码或如何修复它的解释。我认为故障与 rng.Cells.Find... 有关,因为那是在单步执行代码时出现错误的时候,但我可能一辈子都不明白为什么。

失败是因为

rng.Cells.Find("*", LookIn:=xlValues, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Value

如果 Range.Find method 找不到任何东西 returns Nothing 然后你尝试获取 Nothing.Value 但失败了。

在使用 Nothing 之前,请始终测试 Find 的结果:

Dim FoundAt As Range
Set FoundAt = rng.Cells.Find("*", LookIn:=xlValues, SearchOrder:=xlByRows, SearchDirection:=xlPrevious)

If Not FoundAt Is Nothing Then
    Debug.Print FoundAt.Value 'now you can safely use .Value
Else
    MsgBox "Nothing found"
End If 

Find() returns一个Range,如果没有找到,那么这个Range就是Nothing。因此,应该针对 Is Nothing 进行检查。

在下面的代码中,引入了一个新的范围变量,result。检查为无:

Private Sub UserForm_Initialize()
    Dim tbl As ListObject, rng As Range

    Set tbl = Worksheets("Sheet1").ListObjects("table1")
    Set rng = tbl.ListColumns("ID").DataBodyRange

    Dim result As Range
    Set result = rng.Cells.Find("*", LookIn:=xlValues, _ 
                  SearchOrder:=xlByRows, SearchDirection:=xlPrevious)

    If Not result Is Nothing Then
        Debug.Print result.Address
    Else
        Debug.Print "result is nothing"
    End If

End Sub

仅供参考,您并不需要 Find 因为您可以直接获取最后一个单元格:

Private Sub UserForm_Initialize()
    Dim tbl As ListObject, rng As Range, lastCell As Range

    Set tbl = Worksheets("Sheet1").ListObjects("table1")
    Set rng = tbl.ListColumns("ID").DataBodyRange
    With rng
        Set lastCell = .Cells(.Cells.Count)
    End With
    If IsEmpty(lastCell) Then
        Me.TextBox.Value = 1
    Else
        Me.TextBox.Value = lastCell.Value + 1
    End If

End Sub