简体   繁体   中英

Copy and Paste Excel Cells With Exceptions - VBA

I have an excel file with checkboxes and when a checkbox is ticked the VBA code copies the required cells in that row when the linked cell states TRUE. Please see example below.

[Private Sub CommandButton1_Click()
Dim lastrow As Long, erow As Long
'to check the last filled row on sheet named one
lastrow = Worksheets("one").Cells(Rows.Count, 2).End(xlUp).Row
For i = 2 To lastrow
If Worksheets("one").Cells(i, 4).Value = "TRUE" Then
Worksheets("one").Cells(i, 2).Copy
erow = Worksheets("two").Cells(Rows.Count, 1).End(xlUp).Row
Worksheets("one").Paste Destination:=Worksheets("two").Cells(erow + 1, 1)
Worksheets("one").Cells(i, 5).Copy
Worksheets("one").Paste Destination:=Worksheets("two").Cells(erow + 1, 2)
End If
Next i
End Sub]

However I would like to know if there is a way I could add an exception? So if the linked cell states TRUE and another cell in the same row states NEVER, to not copy and paste that row but still paste all other instances where TRUE is located.

Something like the following:

Option Explicit
Private Sub CommandButton1_Click()
    Dim lastrow As Long, erow As Long, i As Long
    Application.ScreenUpdating = False
    With Worksheets("one")
        lastrow = .Cells(Rows.Count, 2).End(xlUp).Row
        For i = 2 To lastrow
            If .Cells(i, 4).Value And .Rows(i).Find("NEVER", LookIn:=xlValues, LookAt:=xlWhole) Is Nothing Then
                 erow = Worksheets("two").Cells(Rows.Count, 1).End(xlUp).Row
                 Worksheets("two").Cells(erow + 1, 1) = .Cells(i, 2)
                 Worksheets("two").Cells(erow + 1, 2) = .Cells(i, 5)
            End If
        Next i
    End With
    Application.ScreenUpdating = True
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