VBA中的列比较错误

您好,我正在写一个macros,比较Excel中不同工作表上的两列。 macros观如下:

Sub Main() Application.ScreenUpdating = False Dim stNow As Date stNow = Now Dim arr As Variant arr = Worksheets("Sheet2").Range("W3:W" & Range("W" & Rows.Count).End(xlUp).Row).Value Dim varr As Variant varr = Worksheets("Sheet3").Range("P3:P" & Range("P" & Rows.Count).End(xlUp).Row).Value Dim x, y, match As Boolean For Each x In arr match = False For Each y In varr If x = y Then match = True Next y If Not match Then Worksheets("Sheet1").Range("L" & Range("L" & Rows.Count).End(xlUp).Row + 1) = x End If Next Debug.Print DateDiff("s", stNow, Now) Application.ScreenUpdating = True End Sub 

如果柱子在同一张纸上,并且代码中没有工作表参考,则工作正常。 但是现在它只复制Sheet3列W中的第一个单元格,尽pipe这个值已经存在于Sheet3中的P列中。

正如你注意到,当没有工作表引用,它工作正常。

你需要始终限定Range()Rows.Columns. ,否则会使用ActiveSheet

以下应该为你工作。

 Sub Main() Application.ScreenUpdating = False Dim stNow As Date stNow = Now Dim arr As Variant With Worksheets("Sheet2") arr = .Range("W3:W" & .Range("W" & .Rows.Count).End(xlUp).Row).Value End With Dim varr As Variant With Worksheets("Sheet3") varr = .Range("P3:P" & .Range("P" & .Rows.Count).End(xlUp).Row).Value End With Dim x, y, match As Boolean For Each x In arr match = False For Each y In varr If x = y Then match = True Exit For End If Next y If Not match Then With Worksheets("Sheet1") .Range("L" & .Range("L" & .Rows.Count).End(xlUp).Row + 1) = x End With End If Next Debug.Print DateDiff("s", stNow, Now) Application.ScreenUpdating = True End Sub 

注:我添加了语句以减less使用Worksheets("Sheetx").的重复性Worksheets("Sheetx"). 另外,根据@ ScottCraner的评论更新了If x = y语句。

另外我看到你有一些未声明的variables。 我build议在一开始( Sub Main()之前Sub Main()添加Option Explicit并声明所有的variables。

在@BruceWayne之后,可以replace代码的中间部分,而不是使用2 x For循环扫描每个数组内的所有元素,只能使用1个For循环,另一个将使用Application.Match函数find数组之间的匹配。

在比较大型数组时,这会为您节省大量的代码运行时间。

注意 :我用isMatchreplace了你的matchvariables, match不是variables的最好名字(因为有一个同名的函数)

编辑1 :删除了isMatchvariables,因为它不需要。

子码

 Dim x For Each x In arr If IsError(Application.Match(x, varr, 0)) Then '<-- no match between elements inside arrays With Worksheets("Sheet1") .Range("L" & .Range("L" & .Rows.Count).End(xlUp).Row + 1) = x End With Else '<-- there is a match between arrays ' do nothing , raise a "MsgBox" End If Next x