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 

尝试这个。 我在下面的行中添加了对我进行更改的评论。

 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的build议。