我有一些VBA的示例,它查找了2列的串联。这将查找数据库源,行数介于35k和250k之间。
执行vlookups的速度太慢,时间从60到500秒。什么是获得相同结果的最有效方法。
序列
取值
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
答案 0 :(得分:1)
据我所知,你的问题在于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 Query中使用此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刷新查询或右键单击并点击刷新。
两种方式: