簡體   English   中英

Excel VBA在大范圍內通過2種條件加速了Vlookup

[英]Excel VBA speed up Vlookup with 2 conditions over a large range

我有一些VBA的示例,該示例查找2列的串聯。 這將查找數據庫供稿,行數介於35k和250k之間。

在60到500秒的時間內執行vlookups太慢了。 獲得相同結果的最有效方法是什么。

序列

  • 屏幕更新次數
  • 關閉所有計算
  • 禁用數據庫
  • 清除剪貼板緩存
  • 刷新數據庫數據
  • 設置查詢
  • 打開計算
  • 關閉計算
  • 復制並粘貼vlookup的值。
  • 啟用數據庫
  • 重新打開所有內容

小號

 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

解決方案1

評論中已經提出了2個解決方案:

  1. 二進制VLOOKUP-參見此處
  2. 減少您的VLOOKUP

這些絕對可以優化您的公式,但是如果您希望查詢在最大幾秒鍾內運行,請使用MS Query ...

解決方案2(最快-幾秒)

在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刷新查詢或右鍵單擊並單擊刷新。

如何在Excel中創建MS查詢?

兩種方式:

  1. 轉到數據 -> 從其他來源 -> 從Microsoft Query
  2. 在此處下載我的SQL AddIn(免費和開放源代碼),只需輸入查詢(F1)的輸出范圍,然后輸入SQL並單擊“ 確定”即可

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM