我正在尝试将简单的数据输入到用户表单中的两个文本框中,然后将此数据添加到名为"AvantAct"的表中。我希望每次运行用户表单时将数据输入到表中的第一个空白行中。有趣的是,我第一次这样做时,它完美无缺。但是,退出工作簿后,稍后又回到工作簿,我似乎得到:-
运行时错误"91":对象变量或未设置块变量。
调试时,突出显示以下行:
tbl.DataBodyRange(lrow2, 1). Value = Me.TxtDate.Value
我应该补充一点,我的表目前是一个空的(新插入的)表。它有 8 列(带标题)、一个空行(来自插入)和一个总计行。
有什么建议吗?
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
由于计数不大于零(为零),因此从未设置lrow
因此出现错误。
If tbl.ListRows.Count = 0 Then
tbl.ListRows.Add
else
Set lrow = tbl.ListRows(tbl.ListRows.Count).Range
...
End If
此外,您的问题问:-
代码我希望将数据输入到第一个空白行中
没有这样做,代码只检查最后一行,如果它还没有空,则添加一行,所以在一个列表中,在 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