简体   繁体   中英

Copy row to another sheet in excel using VBA

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM