VBA比较两列并复制行

时间:2018-07-02 17:58:36

标签: excel vba excel-vba

在Excel中,我试图创建一个宏,该宏可以连续检查两个条件并将其复制到另一页。到目前为止,这就是我所拥有的。如果我取出所有AK引用,则它确实适用于第一个变量,但是第二个变量使我感到悲伤。有什么想法吗?谢谢您的宝贵时间。

Sub GenMonthWeekend()
Dim aj As Range
Dim ak As Range
Dim abc As Integer
Dim Source As Worksheet
Dim Target As Worksheet

' Change worksheet designations as needed
Set Source = ActiveWorkbook.Worksheets("Month Raw Data")
Set Target = ActiveWorkbook.Worksheets("Month Volume - Weekend")

abc = 2     ' Start copying to row 2 in target sheet
For Each aj In Source.Range("aj1:ak10000")   ' Do 10000 rows
    If aj = "1" And ak = "False" Then ' If colum aj is 1 and ak false copy
       Source.Rows(aj.Row).Copy Target.Rows(abc)
       abc = abc + 1
ElseIf aj = "7" And ak = "False" Then ' If colum aj is 7 and ak false copy
       Source.Rows(aj.Row).Copy Target.Rows(abc)
       abc = abc + 1
    End If
Next aj
End Sub

1 个答案:

答案 0 :(得分:2)

您的范围变量ak不能按照您认为的方式工作。

只需遍历您的列AJ并使用AK来检查Offset(,1)中的值,该值将向右看一列。

abc = 2
For Each aj In Source.Range("AJ1000")
    If aj = "1" And aj.offset(,1) = "False" Then
       Source.Rows(aj.Row).Copy Target.Rows(abc)
       abc = abc + 1
ElseIf aj = "7" And aj.offset(,1) = "False" Then
       Source.Rows(aj.Row).Copy Target.Rows(abc)
       abc = abc + 1
    End If
Next aj

您可以通过合并条件并使用For i循环来进行清理。

Sub GenMonthWeekend()
Dim i As Range

Dim Source As Worksheet: Set Source = ActiveWorkbook.Worksheets("Month Raw Data")
Dim Target As Worksheet: Set Target = ActiveWorkbook.Worksheets("Month Volume - Weekend")

For i = 2 To 1000
    If (Source.Range("AJ" & i) = 1 Or Source.Range("AJ" & i) = 7) And Source.Range("AJ" & i).Offset(, 1) = "False" Then
        Source.Rows(i).Copy Target.Rows(Target.Range("A" & Target.Rows.Count).End(xlUp).Offset(1).Row)
    End If
Next i

End Sub