使用 VBA 代码更快地应用 XLOOKUP
使用变量通过 VBA 代码更快地应用 XLOOKUP
使用脚本字典通过 VBA 代码更快地应用 XLOOKUP
使用脚本 ubound 通过 VBA 代码更快地应用 XLOOKUP
使用脚本字典通过 VBA 代码更快地应用 XLOOKUP
子ApplyMultipleXLookupsWithDictionary() Dim wsSrc 作为工作表,wsTgt 作为工作表 Dim lastRowSrc As Long、lastRowTgt As Long、i As Long 昏暗的lookupDict作为对象,键作为变体,结果作为变体 昏暗的源数据作为变体,输出数据作为变体
' Initialize dictionary and worksheets
Set lookupDict = CreateObject("Scripting.Dictionary")
Set wsSrc = ThisWorkbook.Sheets("Sheet1")
Set wsTgt = ThisWorkbook.Sheets("Sheet2")
' Load source data into a dictionary
sourceData = wsSrc.Range("A1:E" & wsSrc.Cells(wsSrc.Rows.Count, "A").End(xlUp).Row).Value
For i = 1 To UBound(sourceData, 1)
key = sourceData(i, 1)
If Not lookupDict.Exists(key) Then
lookupDict(key) = Array(sourceData(i, 2), sourceData(i, 3), sourceData(i, 4)) ' Only B, C, E
End If
Next i
' Disable updates for performance
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
' Load target data and prepare output
lastRowTgt = wsTgt.Cells(wsTgt.Rows.Count, "A").End(xlUp).Row
ReDim outputData(1 To lastRowTgt - 1, 1 To 9) ' Columns B to J
For i = 2 To lastRowTgt
key = wsTgt.Cells(i, 1).Value
If lookupDict.Exists(key) Then
result = lookupDict(key)
outputData(i - 1, 1) = result(0) ' Column B
outputData(i - 1, 2) = result(0) ' Column C
outputData(i - 1, 3) = result(1) ' Column E
outputData(i - 1, 4) = result(1) ' Column F
outputData(i - 1, 5) = result(2) ' Column H
Else
FillNotFound outputData, i - 1
End If
Next i
' Write output data back to the target sheet
wsTgt.Range("B2:H" & lastRowTgt).Value = outputData
' Apply XLOOKUP formulas
For i = 2 To lastRowTgt
With wsTgt
.Cells(i, 2).Formula = "=XLOOKUP(A" & i & ", Sheet1!A:A, Sheet1!B:B, ""not found"", 0, 1)"
.Cells(i, 3).Formula = "=XLOOKUP(A" & i & ", Sheet1!A:A, Sheet1!B:B, ""not found"", 0, -1)"
.Cells(i, 5).Formula = "=XLOOKUP(A" & i & ", Sheet1!A:A, Sheet1!C:C, ""not found"", 0, 1)"
.Cells(i, 6).Formula = "=XLOOKUP(A" & i & ", Sheet1!A:A, Sheet1!C:C, ""not found"", 0, -1)"
.Cells(i, 8).Formula = "=XLOOKUP(A" & i & ", Sheet1!A:A, Sheet1!E:E, ""not found"", 0, -1)"
End With
Next i
' Re-enable updates
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
MsgBox "XLOOKUP operations completed.", vbInformation
结束子
Sub FillNotFound(输出数据为变体,索引为长) 昏暗只要长 For j = 1 To 5 ' 填充 B 至 F 列 输出数据(索引,j)=“未找到” 下一个 结束子