編輯的方法:而不是爲我的解決方案,使用類似比較快2列
For i = 1 To tmpRngSrcMax
If rngSrc(i) <> rngDes(i) Then ...
Next i
這大約要快100倍。
我必須使用VBA比較包含字符串數據的兩列。這是我的方法:
Set rngDes = wsDes.Range("A2:A" & wsDes.Cells(Rows.Count, 1).End(xlUp).Row)
Set rngSrc = wsSrc.Range("I3:I" & wsSrc.Cells(Rows.Count, 1).End(xlUp).Row)
tmpRngSrcMax = wsSrc.Cells(Rows.Count, 1).End(xlUp).Row
cntNewItems = 0
For Each x In rngSrc
tmpFound = Application.WorksheetFunction.CountIf(rngDes, x.Row)
Application.StatusBar = "Processed: " & x.Row & " of " & tmpRngSrcMax & "/" & Format(x.Row/tmpRngSrcMax, "Percent")
DoEvents ' keeps Excel away from the "Not responding" state
If tmpFound = 0 Then ' new item
cntNewItems = cntNewItems + 1
tmpLastRow = wsDes.Cells(Rows.Count, 1).End(xlUp).Row + 1 ' first empty row on target sheet
wsDes.Cells(tmpLastRow, 1) = wsSrc.Cells(x.Row, 9)
End If
Next x
所以,我用一個For Each循環來遍歷槽1日(SRC)柱,和COUNTIF方法來檢查,如果該項目是在第二個已經存在(DES)柱。如果不是,則複製到第一個(src)列的末尾。
該代碼可以工作,但在我的機器上,大約需要7000行的列需要200秒。我注意到當直接用作公式時,CountIf的工作方式更快。
有沒有人有代碼優化的想法?
你可以使用一個O(n)的算法,如果對數據進行排序。這將是我的優化方法。 – Bathsheba
忘記使用Worksheetfucntion來處理如此龐大的數據。將數據複製到數組,然後進行比較。你會驚喜於速度;) –
'ScreenUpdating = false'在你的代碼開始處也會有所幫助。 –