自动将Sheet1中的行复制到Sheet2

时间:2014-03-10 08:52:12

标签: excel vba excel-vba

我想在sheet1中添加新行时自动将Sheet1中的行复制到Sheet2。

1 个答案:

答案 0 :(得分:1)

嗯,这可以更简单地完成我的想法,但是因为你要求如何用VBA这样做,这里是如何用VBA做的。

'This goes in the Sheet1 code window
Private Sub Worksheet_Change(ByVal Target As Range)
Dim rws&
rws = Sheets("Sheet1").Range([A1], ActiveSheet.usedRange).Rows.Count
Application.EnableEvents = False

Dim i As Integer
Dim n As Integer

For i = 1 To rws
    For n = 1 To 30
     Sheet2.Cells(i, n).Value = Sheet1.Cells(i, n).Value
    Next n
Next i

Application.EnableEvents = True

End Sub

这会将活动行和列1-30复制到Excel文件中的Sheet2,以使代码复制更多列编辑For n = 1 To 30的值。

编辑:在Jean-FrançoisCorbett亲切地指出我忘了提到我只包括30列之后编辑。

Edit2:用于插入行而不是直接复制值的代码 - 请注意,此代码只是插入一行并复制我使用simple = Sum测试的数据,它似乎运行良好。

Dim curRow As Integer

Private Sub Worksheet_Change(ByVal Target As Range)
Dim rws&
rws = Sheets("Sheet1").Range([A1], ActiveSheet.UsedRange).Rows.Count
Application.EnableEvents = False

Dim i As Integer
Dim n As Integer

For i = 1 To rws
    For n = 1 To 30
        If i > curRow Then
            Sheet2.Cells(i, n).Insert Shift:=xlDown
        End If
        Sheet2.Cells(i, n).Value = Sheet1.Cells(i, n).Value
    Next n

Next i
curRow = rws
Application.EnableEvents = True

End Sub