【发布时间】:2016-06-08 19:29:54
【问题描述】:
我必须处理大量 Excel 工作表(第 7500 和 16000 行)。我需要查看列表一中的哪些项目不在列表二中...以及列表二中的哪些项目不在列表一中,然后将这些结果粘贴到第三张纸上。
我决定将这两个列表存储在两个集合中。到目前为止,效果很好。当我尝试遍历集合以查找不匹配的内容时,我的计算机因文件太大而冻结。
如何更改我的代码以使其更快?我觉得必须有更好的方法来做到这一点,而不是循环遍历列表一中的每个 i 和列表二中的每个 z。
谢谢!
Sub FullListCompareFSvDF()
Worksheets("FundserveFL").Activate
'Open New Collection and define every variable
Dim FSTrades As New Collection
Dim c As Long
Dim i As Long
Dim z As Long
Dim searchFor As String
'enter the items into the list. There are blank rows and so the first IF Statement is to ignore these.
' The Else Statement shows an account number as the item and an account number & balance (FS.Offset(0,6).Value) as the key
Dim FS As Range
For Each FS In Sheet1.Range("L:L")
If FS = "" Then
Else: FSTrades.Add CStr(FS.Value & " " & FS.Offset(0, 6).Value)
End If
Next
Worksheets("DatafileFL").Activate
Dim DFTrades As New Collection
'enter the items into the list. There are blank rows as well as random numbers and so the first IF Statement is to ignore these (all account numbers are greater than 10000
'"Matching" is displayed for all errors - during an error read the account number from two columns over.
' The Else Statement shows an account number as the item and an account number & balance (FS.Offset(0,6).Value) as the key
Dim DF As Range
For Each DF In Sheet2.Range("H:H")
If DF = "" Or Not IsNumeric(DF.Offset(0, 2)) Or DF < 10000 Then
ElseIf DF.Offset(0, -4) = "MATCHING" Then
DFTrades.Add CStr(DF.Offset(0, 2).Value & " " & DF.Value)
Else:
DFTrades.Add CStr(DF.Value & " " & DF.Offset(0, -2).Value)
End If
Next
'loop through the first collection. Find the first item and try to match it with the items in the second collection.
'Collection 1 Item 1... is it in Collection 2 Item 1? No - then is it in Collection 2 Item 2? When a match is found, move on to Collection 1 Item 2... If no match is found send the item to "ForInvestigation" worksheet
For i = 1 To FSTrades.Count
searchFor = FSTrades(i)
z = 0
Do
z = z + 1
If z > DFTrades.Count Then
c = c + 1
Worksheets("ForInvestigation").Activate
Cells(c, 1).Value = DFTrades(i)
Exit Do
Else:
If DFTrades(z) = searchFor Then
Exit Do
End If
End If
Loop
Next
'Clear Collections
Set FSTrades = Nothing
Set DFTrades = Nothing
End Sub
【问题讨论】:
-
一方面,你为什么要遍历整个
H:H范围?这不会遍历H列的所有数百万行,其中大部分都是空白的吗?与L:L相同。 -
嗨,Marc - 是的,我正在循环整个范围。我不确定如何避免这种情况。你有什么想法?请记住,该列表不是一成不变的。它有断断续续的空白行,每次使用宏时列表的大小都不同。
-
谢谢大卫 - 我正在阅读这篇文章。如果可能的话,我将在下面与 Ron 的答案一起实施。
-
@DavidZemens 好点。其他列中的数据可能低于
L列中的最后一个条目。
标签: arrays excel performance vba list