如何在两个不同的Excel工作表中循环两个范围?

时间:2015-08-20 08:45:12

标签: excel-vba foreach vba excel

所以,我有两张不同的表格。

第一张表是成品清单及其组成部分,如下所示:

A | B |

A | C |

A | D |

B | C |

B | E |

第二个表是第一个表的摘录,只包含一个成品,如下所示:

A | B |

A | C |

A | D |

我尝试并编写了一个代码,用于检查Table2中的每一行,第二列中的值是否存在于Table1的第二列中,以及第一列(Table1中)旁边的值是否存在在表2的第二列中,如果是,则删除Table2的行(正在检查)。

在上面的示例中,它将删除第二行 - | A | C | - 表2中,有一行| B | C |在表1中,B表示在表2的第二列中。

这是我的代码:

    Sub CheckAndDel()
        Dim cll As Range
        Dim rngTmp As Range
        Dim rngMas As Range
        Dim cllToCheck As Range
        Dim LastRow As Long
        Dim LastRowTmp As Long
        Dim Tmp As Worksheet
        Dim Ms As Worksheet

        Set Tmp = Sheets("Temp")
        Set Ms = Sheets("MasterList")

        LastRowTmp = Range("A" & Tmp.Rows.Count).End(xlUp).Row
        LastRow = Range("A" & Ms.Rows.Count).End(xlUp).Row


        Set rngTmp = Tmp.Range("B2:B" & LastRowTmp)
        Set rngMas = Ms.Range("B2:B" & LastRow)



        For Each cllToCheck In rngTmp
            For Each cll In rngMas
                If cll.Value = cllToCheck.Value And _
                WorksheetFunction.CountIf(rngTmp, Range("A" & cll.Row).Value) > 0 Then
                    Rows(cllToCheck.Row).EntireRow.Delete

            Exit For
                End If
            Next
         Next

    End Sub

到目前为止,它只能正确检测和删除一行。无法弄清楚原因。 用AutoFilter替换嵌套循环是一个好主意(甚至可能)?

2 个答案:

答案 0 :(得分:0)

你写了Exit for所以第一次条件成立时,你退出循环。只需评论此行,看看会发生什么 的修改
对,抱歉。仔细观察后:你必须精确化变量表LastRowTmpLastRow(否则它将采用活动表),所以你必须写:

    LastRowTmp = Tmp.Range("A" & Tmp.Rows.Count).End(xlUp).Row
    LastRow = Ms.Range("A" & Ms.Rows.Count).End(xlUp).Row

还要更改此行以避免出现问题:
Tmp.Rows(cllToCheck.Row).EntireRow.Delete
我用这些更改测试你的代码,它适用于我

答案 1 :(得分:0)

原来从最后一行删除效率更高,所以为了免费知识,这是工作代码:

    Sub test()


    Dim cll As Range
    Dim rngTmp As Range
    Dim rngMas As Range
    Dim cllToCheck As Range
    Dim LastRow As Long
    Dim LastRowTmp As Long
    Dim Tmp As Worksheet
    Dim Ms As Worksheet
    Dim Firstrow As Long
    Dim LastRowTst As Long
    Dim i As Long


    Set Tmp = Sheets("Temp")
    Set Ms = Sheets("MasterList")

    Firstrow = Tmp.UsedRange.Cells(1).Row
    LastRowTst = Tmp.UsedRange.Rows(Tmp.UsedRange.Rows.Count).Row

    LastRowTmp = Tmp.Range("A" & Tmp.Rows.Count).End(xlUp).Row
    LastRow = Ms.Range("A" & Ms.Rows.Count).End(xlUp).Row

    Set rngTmp = Tmp.Range("B1:B" & LastRowTmp)
    Set rngMas = Ms.Range("B1:B" & LastRow)


    For i = LastRowTst To Firstrow Step -1
         Set cllToCheck = Tmp.Range("B" & i)
        For Each cll In rngMas
            If cll.Value = cllToCheck.Value And WorksheetFunction.CountIf(rngTmp, Ms.Range("A" & cll.Row).Value) >= 1 Then
                Tmp.Rows(cllToCheck.Row).EntireRow.Delete
               Exit For
               End If
        Next
    Next i
End Sub