![](/img/trans.png)
[英]Is there a way to speed up this VBA macro running to perform a Vlookup on a large range 1000's of times?
[英]Excel VBA speed up Vlookup with 2 conditions over a large range
我有一些VBA的示例,該示例查找2列的串聯。 這將查找數據庫供稿,行數介於35k和250k之間。
在60到500秒的時間內執行vlookups太慢了。 獲得相同結果的最有效方法是什么。
序列
小號
Sub startcom()
Dim ii As Long, lastrow As Long
Dim StartTime As Double
Dim SecondsElapsed As Double
' starts timer
StartTime = Timer
'freeze screens, clears cache and stops cals
stopall
'Set error traps and start and end times
On Error GoTo errortrap:
Set sht1 = wsRag
Set sht2 = wsComdata
sht2.Select
reflist
'Find the last row (in column A) with data. and set start row for data copy
lastrow = sht1.Range("A:A").Find("*", SearchDirection:=xlPrevious).Row
ii = 9
'disables db connection
wsConfig.Cells(7, 2) = 0
sht1.Select
Range("AM" & ii & ":AM" & lastrow).Formula = "=IF(VLOOKUP(CONCATENATE(A"& ii &",B" & ii &"),Comment_data!A:F,4,0)="""","""",VLOOKUP(CONCATENATE(A" & ii & ",B" & ii & "),Comment_data!A:F,4,0))" ' Get comments
calcon
calcoff
Range("AM" & ii & ":AM" & lastrow & "").Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
'enable DB connection
wsConfig.Cells(7, 2) = 1
'Determine how many seconds code took to run
SecondsElapsed = Round(Timer - StartTime, 2)
'get lenghth of runtime
Debug.Print "Ran successfully in " & SecondsElapsed & " seconds", vbInformation
startall
Exit Sub
errortrap:
errormess
Debug.Print "Location: Comments start"
End Sub
據我了解,您的問題出在VLOOKUP操作上 ,這是這里(分散了幾行以使其更具可讀性):
Range("AM" & ii & ":AM" & lastrow).Formula =
"=IF(
VLOOKUP(CONCATENATE(A"& ii &",B" & ii &"),Comment_data!A:F,4,0)="""",
"""",
VLOOKUP(CONCATENATE(A" & ii & ",B" & ii & "),Comment_data!A:F,4,0)
)" ' Get comments
評論中已經提出了2個解決方案:
這些絕對可以優化您的公式,但是如果您希望查詢在最大幾秒鍾內運行,請使用MS Query ...
在MS查詢中使用以下SQL:
SELECT com.F FROM [CurrentSheet$] as curr
LEFT JOIN [Comment_data$] as com
ON (curr.A + curr.B) = com.A
這就是它的工作方式。 下面,我創建了兩個示例表。
工作表名稱: CurrentSheet
工作表名稱: Comment_data
CurrentSheet中的F列是MS查詢(附加到原始表中)。 您需要做的就是使用VBA刷新查詢或右鍵單擊並單擊刷新。
兩種方式:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.