我正在尝试将简单数据输入到用户表单中的两个文本框中,然后将此数据添加到名为“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
答案 0 :(得分:0)
问题来自于开始使用空表。
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