简体   繁体   中英

Copy and paste to another workbook if criteria is met

I am trying to create VBA code which copies rows from one workbook (Test Report.xlsx) and then pastes that copied row into another workbook(Test Final Report.xlsx), if it meets specific criteria when the commandbutton is clicked. The criteria to copy and paste is a if a cell in the second column in the table contains the critera 3'5, copy that row and then paste it into another workbook. I've tried the following but when I go to run, it just selects cells specified in the line of code before End Sub. I need assistance with this, please see below the code which keeps failing me. What am I doing wrong and what should I do to make it right?

Private Sub CommandButton1_Click()
    a = Worksheets("Mar'19").Cells(Rows.Count, 1).End(xlUp).Row

    For i = 2 To a
        If Worksheets("Mar'19").Cells(i, 2).Value = "3'5" Then
            Worksheets("Mar'19").Rows(i).Copy
            Worksheets("3.5").Activate
            b = Worksheets("3.5").Cells(Rows.Count, b).End(xlUp).Row
            Worksheets("Sheet2").Cells(b + 1, 1).Select
            ActiveSheet.Paste
            Worksheets("Sheet1").Activate
        End If
    Next

    Application.CutCopyMode = False
    ThisWorkbook.Worksheets("Mar'19").Cells(1, 1).Select
End Sub

Does this work?

Private Sub test()
    a = Worksheets("Mar'19").Cells(Rows.Count, 1).End(xlUp).Row
For i = 2 To a
    If Worksheets("Mar'19").Cells(i, 2).Value = "3'5" Then
        Worksheets("Mar'19").Rows(i).Copy
        Worksheets("3.5").Cells(ThisWorkbook.Sheets("3.5").Cells(1048576, 1).End(xlUp).row + 1, 1).Paste

    End If
Next

Application.CutCopyMode = False
ThisWorkbook.Worksheets("Mar'19").Cells(1, 1).Select
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