【发布时间】:2019-03-06 11:37:48
【问题描述】:
我有 VBA 代码向表中添加新行(数据从第 5 行开始)。
我制作了一张新表格,当表格没有标题时效果很好。但是,当我添加标题时,会弹出以下错误
运行时错误“1004”这不起作用,因为它会 在工作表的表格中移动单元格。
我点击调试,它突出显示Rng.Insert Shift:=x1Down
错误的原因是什么,如何纠正?
Sub AddRows()
Const BaseRow As Long = 5 ' modify to suit
Dim x As String ' InputBox returns text if 'Type' isn't specified
Dim Rng As Range
Dim R As Long
x = InputBox("How many rows would you like to add?", "Insert Rows")
If x = "" Then Exit Sub
R = BaseRow + CInt(x) - 1
Rows(BaseRow).Copy 'Copy BaseRow
'specify range to insert new cells
Set Rng = Range(Cells(BaseRow, 1), Cells(R, 1))
Rng.Insert Shift:=xlDown
' insert the new rows BEFORE BaseRow
' to insert below BaseRow use Rng.Offset(BaseRow - R)
Set Rng = Rng.Offset(BaseRow - R - 1).Resize(Rng.Rows.Count, ActiveSheet.UsedRange.Columns.Count)
Rng.Select
On Error Resume Next
Rng.SpecialCells(xlCellTypeConstants).ClearContents
Application.CutCopyMode = False '
End Sub
【问题讨论】:
-
如果你有标题,你的baserow会是+1?
-
在要插入行的表下面还有其他表吗?
-
不,是一张大桌子
-
我试过 R = BaseRow + CInt(x) + 1 但没有任何乐趣。你是这个意思吗?