Excel VBA在大范围内加速2个条件的Vlookup
我有一个VBA的样本,查找2列的串联。 这查找数据库饲料,行数从35k到250k。
做vlookups太慢,时间从60到500秒。 什么是最有效的方式来获得相同的结果。
序列
- 转到屏幕更新
- closures所有计算
- 禁用数据库
- 清除剪贴板caching
- 刷新数据库数据
- 设置查找
- 打开计算
- closures计算
- 复制并粘贴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
解决scheme1
在评论中已经提出了两个解决scheme:
- 二进制VLOOKUP – 请参阅此处
- 减less你的一个VLOOKUP
这些一定会优化你的公式,但如果你想让你的查询在几秒钟内运行, 最大使用MS Query …
解决scheme2(最快的情侣)
在MS Query中使用这个SQL:
SELECT com.F FROM [CurrentSheet$] as curr LEFT JOIN [Comment_data$] as com ON (curr.A + curr.B) = com.A
这是如何工作的。 下面我创build了两个示例表。
工作表名称: CurrentSheet
工作表名称: Comment_data
CurrentSheet中的F列是MS Query(附加到原始表)。 所有你需要做的就是使用VBA刷新查询,或者右击并点击刷新。
如何在Excel中创build一个MS Query?
两种方式:
- 转到数据 – > 从其他来源 – > 从Microsoft Query
- 在这里下载我的SQL AddIn(自由和开放源代码),只需input查询的输出范围(F1)并inputSQL,然后点击Ok