在excel表宏末尾插入行-对象全局的方法范围失败



背景:我在excel中有一个表,随着时间的推移,数据会被添加到其中,为了给我的同事(他们虽然很可爱,但不喜欢修改excel中的东西,因为害怕弄乱)一个简单的选择,如果我不在的时候表满了,我想添加一个宏按钮,向表中添加更多的行并填充格式(一些单元格在&大多数单元格中具有条件格式)。这个想法是,他们可以填满表格的最后一行,但不包括表格的最后行,然后点击按钮,它会在表格的最后行都添加20行左右的新行,并将最后一行的格式复制到其中。到目前为止,这是我的代码:

Sub Add_Rows()
Dim ws As Worksheet
Set ws = ActiveSheet
Dim tbl As ListObject
Set tbl = ws.ListObjects("Table1")
x = tbl.Range.Rows.Count
Range(x - 1, x + 19).Insert Shift:=xlShiftDown, CopyOrigin:=xlFormatFromRightOrBelow
End Sub

我得到了一个";运行时错误"1004"object_global的方法范围失败";当我尝试点击按钮时;插入";行作为问题。我是vba的新手,所以欢迎任何建议。如果我的代码完全是无稽之谈,那么我们将不胜感激。这也是第二个版本,我的第一个循环Rows.Add有效,但需要几秒钟的时间,所以我希望插入20会比添加20次快!

试试这个。

Sub Add_Rows()
Dim ws As Worksheet
Set ws = ActiveSheet
Dim tbl As ListObject
Dim lastRow As Range, newRng As Range
Dim newRows As Integer: newRows = 20

Set tbl = ws.ListObjects("Table1")

' Last row
On Error GoTo resizeOnly    ' Listrows = 0
Set lastRow = tbl.ListRows(tbl.ListRows.Count).Range
On Error GoTo 0

' range of new rows
Set newRng = tbl.ListRows(tbl.ListRows.Count).Range.Resize(newRows).Offset(1)

' resize table
tbl.Resize tbl.Range.Resize(tbl.Range.Rows.Count + newRows, tbl.Range.Columns.Count)
' copy last format to new rows
lastRow.Copy
newRng.PasteSpecial xlPasteFormulasAndNumberFormats

Application.CutCopyMode = False

Exit Sub

resizeOnly:
' resize table
tbl.Resize tbl.Range.Resize(tbl.Range.Rows.Count + newRows, tbl.Range.Columns.Count)
End Sub

如果表下面没有数据,可以直接为表后面的行赋值。只要每行中至少有一个单元格具有定义良好的数据,表就会自动展开以包含新行。

' Insert 3 new rows into the listoject
' We assume the ListObject already contains data
Public Sub Test(Lob As ListObject)
Dim Sht As Worksheet
Dim StartRow As Long, StartCol As Long, NumCols As Long
Dim Lst As Variant
Dim Rng As Range

' Allocate 3 new rows
NumCols = Lob.ListColumns.Count
ReDim Lst(1 to 3, 1 to NumCols)


' Get the first column of and the first row following the list table
StartCol = Lob.Range.Column
StartRow = Lob.Range.row + Lob.Range.Rows.Count

' Create a range big enough to hold the data, immediately under the last row of the table.
Set Sht = Lob.Parent
Set Rng = Sht.Cells(StartRow, StartCol).Resize(UBound(Lst), UBound(Lst, 2))

' Add some data to the new rows
Lst(1, 1) = "Test1"
Lst(2, 1) = "Test2"
Lst(3, 1) = "Test3"

' Copy data to the destination
Rng = Lst
End Sub

如果列表对象不包含数据,即Lob.ListRows.Count=0,则在标头之后写入数据,否则在最后一行之后写入数据。

你的代码中有一些错误:

  • "范围(x;当x和y是整数时,将导致错误。如果要引用单元格。尝试单元格(x,y)。或范围(单元格(x1,y1),单元格(x2,y2)),以指代更多单元格
  • Resize()接受两个参数,并返回一个范围——它不会影响工作表上的任何内容

如果需要,请参阅如何插入行:

Excel范围。插入:

文档示例:

With Range("B2:E5")
.Insert xlShiftDown
' Optionally clear formats, which you do not want, if you add to
' a table with well defined data and formats.
.ClearFormats
End With

插入的行数将等于我们称之为插入的范围内的行数。

最新更新