运行时错误'91'将表单添加到用户表单数据

我试图将简单的数据input到一个用户窗体中的两个文本框中,然后将这些数据添加到名为“AvantAct”的表中。 每次运行用户表单时,我都希望将表中的数据input表中的第一个空行。 有趣的是,我第一次做到这一点完美无瑕。 但是,在退出工作簿之后又回来的时候,我似乎得到了: –

运行时错误“91”:对象variables或未设置块variables。

当我debugging下面的行时高亮显示:

tbl.DataBodyRange(lrow2, 1). Value = Me.TxtDate.Value 

我应该补充说,我的表目前是一个空的(新插入的)表。 它有8列(带标题),一个空行(从插入)和一个总行。

有什么build议么?

 Private Sub SubmitButton_Click() Dim ws As Worksheet Dim tbl As ListObject Dim TxtDate As Date Dim TxtPmt As Currency Dim col As Integer Dim lrow As Range Dim lrow2 As Long Set ws = ActiveWorkbook.Worksheets("Avant") Set tbl = ws.ListObjects.Item("AvantAct") If tbl.ListRows.Count > 0 Then Set lrow = tbl.ListRows(tbl.ListRows.Count).Range For col = 1 To lrow.Columns.Count If Trim(CStr(lrow.Cells(1, col).Value)) <> "" Then tbl.ListRows.Add Exit For End If Next col End If lrow2 = tbl.ListRows.Count tbl.DataBodyRange(lrow2, 1).Value = Me.TxtDate.Value tbl.DataBodyRange(lrow2, 3).Value = Me.TxtPmt.Value Unload Me End Sub 

问题来自有一个空表开始。

 If tbl.ListRows.Count > 0 Then Set lrow = tbl.ListRows(tbl.ListRows.Count).Range ... End If 

因为计数不大于零(这是零),所以从未设置过,因此错误。

 If tbl.ListRows.Count = 0 Then tbl.ListRows.Add else Set lrow = tbl.ListRows(tbl.ListRows.Count).Range ... End If 

另外,你的问题问:

我想要input到第一个空白行的数据

代码没有这样做,代码只检查最后一行,并添加一个行,如果它不是已经是空的,所以在列表中的5行中,第三行是空的,第三行不会是使用,但底部的行将被添加。 下面会做你想的: –

 Private Sub SubmitButton_Click() Dim ws As Worksheet Dim tbl As ListObject Dim TxtDate As Date Dim TxtPmt As Currency Dim col As Integer Dim lrow As Range Dim lrow2 As Long Dim BlnYesNo As Boolean Set ws = ActiveWorkbook.Worksheets("Avant") Set tbl = ws.ListObjects.Item("AvantAct") If tbl.ListRows.Count = 0 Then tbl.ListRows.Add lrow2 = 1 Else For lrow2 = 1 To tbl.ListRows.Count Set lrow = tbl.ListRows(lrow2).Range 'If it stays true, we must add a row BlnYesNo = True For col = 1 To lrow.Columns.Count If Trim(CStr(lrow.Cells(1, col).Value)) <> "" Then BlnYesNo = False Exit For End If Next If BlnYesNo Then Exit For Set lrow = Nothing Next 'If its false then all rows had data and we need to add a row If Not BlnYesNo Then tbl.ListRows.Add lrow2 = tbl.ListRows.Count End If End If tbl.DataBodyRange(lrow2, 1).Value = "A" tbl.DataBodyRange(lrow2, 3).Value = "B" Set tbl = Nothing Set ws = Nothing End Sub