简体   繁体   English

复制和粘贴具有异常的Excel单元格-VBA

[英]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. 我有一个带有复选框的excel文件,当选中复选框时,当链接的单元格为TRUE时,VBA代码将复制该行中的所需单元格。 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. 因此,如果链接的单元格的状态为TRUE,而同一行中的另一个单元格的状态为NEVER,则不要复制和粘贴该行,而是仍粘贴位置TRUE的所有其他实例。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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