比较两张纸上的行

时间:2018-09-20 13:23:19

标签: excel vba

Excel文档中有6张纸。
enter image description here

我想比较两张纸。

第1张(Artikelstammdaten)有8555行
enter image description here

第2张(Warengruppen)有232行
enter image description here

我的代码:

i = 0

for row in listSchedule:
    if row[0]=="Download":
        row.append(myOtherList[i])
        i+=1

它可以工作,但在1755行中断。

1 个答案:

答案 0 :(得分:0)

之所以只有1755次迭代,是因为浪费了很多循环才能在Sheets("Warengruppen")中找到匹配的值。使用更明智的方法,Range.Find(What:=key)方法将返回具有相同键的范围对象。请注意,如果没有匹配项,它将返回Nothing,因此我们需要检查是否找到了它,以防止发生错误。

Sub WorksheetLoop()
    'current is crying because you never call her :/
    Dim Current As Range
    Dim Element As Range
    Dim wbFound As Range

    Dim Stamm1 As String
    Dim Stamm2 As String
    Dim Stamm3 As String
    Dim Summe As String

    For Each Element In Sheets("Artikelstammdaten").Range("R:R")

        Set wbFound = Sheets("Warengruppen").Range("A:A").Find(What:=Element.Value)

        If wbFound Is Nothing Then
            Debug.Print "Not Found with Row# " & Element.Row
        Else
            Stamm1 = wbFound.Offset(0, 1)
            Stamm2 = wbFound.Offset(0, 2)
            Stamm3 = wbFound.Offset(0, 3)
            Summe = Stamm1 + ">" + Stamm2 + ">" + Stamm3

            Element.Value = Summe
        End If
    Next Element
End Sub