Excel VBA在比较不同工作表中的两列时崩溃

时间:2016-02-19 13:25:52

标签: excel vba excel-vba

我有这个问题我想将一个工作表中的两列与另一个工作表中的另外两列进行比较,然后如果真的用其他列填充数据。 我写了一些代码,但它只工作到47行。不知道这个问题。 Excel没有响应。这是我的代码。也许有人可以解释我做错了什么

  Sub Compare()
      Dim i, j As Integer
      For i = 2 To 2175
          For j = 2 To 3834

              If (ActiveWorkbook.Worksheets("Arkusz2").Range("B" & i) = ActiveWorkbook.Worksheets("Arkusz3").Range("A" & j) _
              And ActiveWorkbook.Worksheets("Arkusz2").Range("C" & i) = ActiveWorkbook.Worksheets("Arkusz3").Range("B" & j)) _
              Then ActiveWorkbook.Worksheets("Arkusz2").Range("E" & i).Value = ActiveWorkbook.Worksheets("Arkusz3").Range("C" & j).Value

          Next j
      Next i

End Sub

1 个答案:

答案 0 :(得分:1)

试试这个。我在下面的行中添加了评论,我做了更改。

Sub Compare()
    Dim i as Integer, j As Integer
    ' You need to specify the value type for *all* variables

    Dim ws1 as Worksheet, ws2 as Worksheet

    Set ws1 = ActiveWorkbook.Worksheets("Arkusz2")
    Set ws2 = ActiveWorkbook.Worksheets("Arkusz3")
    ' Setting these as their own variables makes the code far more readable

   For i = 2 To 2175
       For j = 2 To 3834

           If (ws1.Range("B" & i).Value = ws2.Range("A" & j).Value _
              And ws1.Range("C" & i).Value = ws2.Range("B" & j).Value) Then 
              ' Make sure you are comparing the VALUES and not the range objects

              ws1.Range("E" & i).Value = ws2.Range("C" & j).Value

              Exit For    
              ' If we've found a match, exit the inner loop early (if it *would* find 
              ' another match, the orig. value would just be overwritten, anyways) 
              ' This will likely reduce the time to complete significantly
            End If

        Next j
     Next i

End Sub

编辑:添加Exit For以在找到匹配后提前退出内部循环。感谢@Tim Williams建议。