以下代码可将新行添加到表末尾并解锁该行。但是,尽管完成了该操作,我仍然收到“运行时错误 424:需要对象”。
不知道为什么会这样。
Sub AddRowToTable()
Dim ws As Worksheet
Dim tbl As ListObject
Dim lastRow As ListRow
Set ws = ActiveSheet
Set tbl = ws.ListObjects("Table1")
tbl.ListRows.Add
Set lastRow = tbl.Range.Rows(tbl.Range.Rows.Count).Row
lastRow.Locked = False
End Sub
使用
tbl.ListRows(tbl.ListRows.Count)
代替 tbl.Range.Rows(tbl.Range.Rows.Count).Row
Sub AddRowToTable()
Dim ws As Worksheet
Dim tbl As ListObject
Dim lastRow As ListRow
Set ws = ActiveSheet
Set tbl = ws.ListObjects("Table1")
tbl.ListRows.Add
Set lastRow = tbl.ListRows(tbl.ListRows.Count)
lastRow.Range.Locked = False
End Sub
我正在使用这个脚本,但这里有一个问题,因为如果我在任何地方写入,然后自动添加一个新行,但我想如果我在最后一行写入,然后添加新行,所以请解决这个问题
私有子工作表_Change(ByVal Target As Range) 将 tbl 调暗为 ListObject 将lastRow 调暗为ListRow 静态标志为布尔值
' Unprotect the sheet
Me.Unprotect Password:="YourPassword" ' Replace "YourPassword" with the actual password
On Error Resume Next ' Ignore errors temporarily
Set tbl = Me.ListObjects("Table1") ' Replace "Table1" with the name of your table
On Error GoTo 0 ' Restore normal error handling
' Check if the table exists and the sheet is unprotected
If Not tbl Is Nothing Then
Set lastRow = tbl.ListRows(tbl.ListRows.Count)
' Check if the last row is the target and is filled; if filled, set flag to prevent further additions
If Target.Row = lastRow.Range.Row + 1 And Application.WorksheetFunction.CountA(lastRow.Range) > 0 Then
flag = True ' Set flag to indicate table is full
End If
End If
If Not flag Then ' Proceed only if the table isn't full
Application.EnableEvents = False ' Disable events to prevent infinite loop
' Unprotect the sheet to allow row addition
Me.Unprotect Password:="YourPassword" ' Replace "YourPassword" with the actual password
' Add a new row to the table
Set lastRow = tbl.ListRows.Add
' Protect the sheet again
Me.Protect Password:="YourPassword" ' Replace "YourPassword" with the actual password
Application.EnableEvents = True ' Enable events
End If
结束子