Excel宏VBA在先前添加的行下方添加行,并复制格式和公式



我创建了一个宏,它在复制上面一行的格式和公式的同时添加了一行。这很好用,代码如下:

Sub New_Line()
Rows("7:7").Select
'Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Rows("6:6").Select
Selection.Copy
Rows("7:7").Select   
Selection.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, _  
SkipBlanks:=False, Transpose:=False
Application.CutCopyMode = False
Range("G6:T6").Select
Selection.AutoFill Destination:=Range("G6:T7"), Type:=xlFillDefault 
Range("G7:T7").Select 
ActiveWindow.ScrollColumn = 1

End Sub

然而,我想在我刚刚使用上面的宏创建的行下添加另一行,依此类推,这样这就可以是一个连续的东西,并且还可以使用前面添加的行中的公式来保持一个连续总数(希望这有意义(。我可以在上面的编码中看到问题所在,宏总是将行添加到第7行,并从第6行复制公式/格式。我尝试过添加+1,但没有成功,我考虑过循环,但这会混淆宏运行。有人能帮忙吗?

提前感谢

啊,宏记录器的诅咒。该死的东西最好被忽略,有时除了一些语法!

试试这个:

nRows = 13 'Define how may rows you are going to copy down
sRow = 7  'The starting row for the paste op (which will copy from sRow-1)
for iRows = 0 to nRows
Rows(sRow+iRows-1).Copy
Rows(sRow+iRows).PasteSpecial Paste:=xlPasteFormats
Rows(sRow+iRows).PasteSpecial Paste:=xlPasteFormulas
next iRows

与任何解决方案一样,我也建议您至少完全符合您所在的工作表,即

for iRows = 0 to nRows
with Sheets("Sheet1")
.Rows(sRow+iRows-1).Copy
.Rows(sRow+iRows).PasteSpecial Paste:=xlPasteFormats
.Rows(sRow+iRows).PasteSpecial Paste:=xlPasteFormulas
end with
next iRows

如果不是工作簿。它让你不那么容易(但不是防弹的(与电脑的互动污染了你的宏。

您也可以尝试";FillDown";根据:Excel VBA:使用公式自动填充多个单元格

如果每次运行时都希望它从最后一行重新启动,则对sRow 使用以下命令

sRow = Sheets("Sheet1").Cells(Sheets("Sheet1").Rows.Count, "A").End(xlUp).Row

这是我使用过的代码:

Sub NewTry1()
nRows = 1 'Define how may rows you are going to copy down
sRow = 7  'The starting row for the paste op (which will copy from sRow-1)
For iRows = 0 To nRows
Rows(sRow + iRows - 1).Copy
Rows(sRow + iRows).PasteSpecial Paste:=xlPasteFormats
Rows(sRow + iRows).PasteSpecial Paste:=xlPasteFormulas
Next iRows
For iRows = 0 To nRows
With Sheets("Main Sheet")
.Rows(sRow + iRows - 1).Copy
.Rows(sRow + iRows).PasteSpecial Paste:=xlPasteFormats
.Rows(sRow + iRows).PasteSpecial Paste:=xlPasteFormulas
End With
Next iRows
End Sub

我是VBA的新手,所以如果我误解了任何领域,我很抱歉!

最新更新