此部分代码旨在调整表的大小,以便从UserForm添加新的数据输入行。目前,当我运行代码时,我得到:
错误9 - 下标超出范围
在线:
Set tbl1 = sht1.ListObjects("LogTable")
这是完整的代码:
Private Sub CommandButton1_Click()
'Start button
'Log start time as the time the button is clicked
Dim EmptyRow, LastRow As Long
Dim sPath As String
Dim tbl1, tbl2 As Range
'Find next empty row based on first column
Set wb = ThisWorkbook
Set sht1 = wb.Sheets("Log")
Set tbl1 = sht1.ListObjects("LogTable")
LastRow = sht1.Cells(sht1.Rows.Count, "A").End(xlUp).Row
EmptyRow = LastRow + 1
tbl1.Resize Range("A2:E" & EmptyRow)
sht1.Cells(EmptyRow, 1).Value = Now
感谢您的帮助!
答案 0 :(得分:1)
试试这段代码:
Dim tbl1 As ListObject
Dim wb As Workbook
Dim sht1 As Worksheet
Set wb = ThisWorkbook
Set sht1 = wb.Sheets("Log")
Set tbl1 = sht1.ListObjects("LogTable")
tbl1.ListRows.Add
请注意:
您的代码包含不正确的声明:EmptyRow
和tbl1
被声明为Variant,这不是您想要的(似乎)。这是一个常见的VBA错误 - 假设类型声明适用于该行上的所有变量。它不是。避免它的最简单方法是始终每行声明一个变量。
此外,tbl1
和tbl2
应声明为表格(ListObject
),而不是范围。