(如果复制)多个变量

时间:2019-05-07 04:52:09

标签: excel vba if-statement copy

我想将数据从一张纸复制到另一张纸。选择部分是根据日期和列的特定值。

enter image description here

我从互联网尝试了此代码。因此,基本逻辑是如果满足2个条件,则复制该行。但是它不起作用。

实际上只在第一个条件被写入时才起作用,而在第二个条件被写入时,VBA没有执行任何操作

Sub CopyRowsAcross()
Dim i As Integer
Dim ws1 As Worksheet: Set ws1 = ThisWorkbook.Sheets("Clean_Sheet")
Dim ws2 As Worksheet: Set ws2 = ThisWorkbook.Sheets("Daily_Report")

For i = 2 To ws1.Range("P65536").End(xlUp).Row
    If ws1.Cells(i, 1) = "DOWNY S.FRESH 900ML"  and ws2.Range ("C2") = ws1.Cells(i,3) Then
    ws1.Rows(i).Copy ws2.Rows(ws2.Cells(ws2.Rows.Count, 2).End(xlUp).Row + 1)
    End If
Next i
End Sub

ws2.Range(“ C2”)被选择的日期写在工作表的单元格C2中。

结果是根据这两个条件复制的行

1 个答案:

答案 0 :(得分:0)

假设您在工作表1中的两个数据都是真正的日期,而C2中的过滤器也是一个日期,则可以这样做:

Option Explicit
Sub CopyRowsAcross()

    Dim LastRow As Long, lrow As Long
    Dim ws1 As Worksheet: Set ws1 = ThisWorkbook.Sheets("Clean_Sheet")
    Dim ws2 As Worksheet: Set ws2 = ThisWorkbook.Sheets("Daily_Report")
    Dim DateFilter As Date

    With ws2
        DateFilter = .Cells(2, 3)
        lrow = .Cells(.Rows.Count, 1).End(xlUp).Row + 1
    End With

    With ws1
        LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row
        .Range("A1:C" & LastRow).AutoFilter Field:=1, Criteria1:="DOWNY S.FRESH 900ML"
        .Range("A1:C" & LastRow).AutoFilter Field:=3, Criteria1:=Format(DateFilter, "dd-Mmm-yy")
        LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row
        If LastRow > 1 Then
            .Range("A2:C" & LastRow).SpecialCells(xlCellTypeVisible).Copy ws2.Cells(lrow, 1)
        End If
        .AutoFilterMode = False
    End With

End Sub

您可以过滤所需的数据并将其全部复制一次,而无需循环(耗时)。