且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用VBA将行复制到Excel中的另一个表

更新时间:2022-10-24 10:20:29

编辑:添加处理多区域选择

  Private Sub Worksheet_Change(ByVal Target As Range)
Dim a As Range,rw As Range
For Each a In Selection.Areas
For each rw In a.Rows
如果rw.Row> = 2然后
rw.EntireRow.Copy Sheet2.Cells(2 +(rw.Row - 2)* 3,1)
End If
Next rw
下一个
End Sub


First off, I have never used VBA (or VB for that matter), so keep that in mind. I am trying to copy a row to another sheet in my workbook. So whenever any change in row 2 will happen in sheet1, that row should be copied in row 2 on sheet2. If row 3 is modified in sheet1, row 5 should be modified on sheet2. I want there to be an empty row between each row on sheet2. I am going to try and create a new table with VBA to place inside this empty row. Anyways, I am getting an error on my Selection.Paste line. I have very limited knowledge (an hours worth) on VBA, so I could be completely off on what I am trying to do.

Private Sub Worksheet_Change(ByVal Target As Range)
 'Do not worry about column headers
  If Target.Row = 1 Then Exit Sub

  'On Error GoTo ErrHandler
  Application.EnableEvents = False 'This might be necessary?

  Sheet1.Rows(Target.Row).Select
  Selection.Copy
  Sheet1.Rows(Target.Row).Copy

  If Target.Row = 2 Then
    Sheet2.Rows(Target.Row).Select
    Selection.Paste
  Else
    Sheet2.Select
    Sheet2.Rows(Target.Row + Target.Row - 1).Select
    Selection.Paste
  End If

ErrHandler:
  Application.EnableEvents = True 'This might be necessary?
End Sub


Edit: After changing Selection.Paste to ActiveSheet.Paste, it is now working.

EDIT: added dealing with multi-area selections

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim a As Range, rw As Range
    For Each a In Selection.Areas
        For Each rw In a.Rows
            If rw.Row >= 2 Then
                rw.EntireRow.Copy Sheet2.Cells(2 + (rw.Row - 2) * 3, 1)
            End If
        Next rw
    Next a
End Sub