如何在数组中查找并找到对应的值

问题描述 投票:0回答:1

我有 2 行数据 - A 列包含“设备 ID”,B 列包含每个 ID 的编号。 @FaneDuru 提供的宏如下:

Sub ExtractMaxPerEquipment()
 Dim ws As Worksheet, lastR As Long, arr, arrFin, i As Long, dict As Object
 
 Set ws = ActiveSheet 'use here the necessary sheet
 lastR = ws.Range("A" & ws.rows.count).End(xlUp).row 'last row in A:A
 
 arr = ws.Range("A2:B" & lastR).Value2 'place the range in an array for faster processing
 
 Set dict = CreateObject("Scripting.Dictionary") 'set the necessary dictionary
 For i = 1 To UBound(arr) 'iterate between the array rows
    dict(arr(i, 1)) = Application.Max(endNo(CStr(arr(i, 2))), dict(arr(i, 1))) 'load the dictionary
 Next i
 
 arrFin = Application.Transpose(Array(dict.keys, dict.Items)) 'combine the dictionary keys and items in an array
 
 ws.Range("D2").Resize(UBound(arrFin), 2).Value2 = arrFin 'drop the final array content in "D2"
End Sub

Function endNo(x As String) As String
    If x = "" Then endNo = 0: Exit Function
    With CreateObject("vbscript.regexp")
        .Pattern = "\d{1,5}?.*$"
        .Global = False
        endNo = .Execute(x)(0)
    End With
End Function

Sample Data

目前,它创建了一个表,其中包含所有唯一设备 ID 以及 D 列和 E 列中每个设备的最高编号。我需要在这个数组中搜索 - 例如,我有一个名为“Asset”的字符串 - 我需要修改宏以在数组的“设备名称”中搜索 Asset 并返回相应的最高值。我该怎么做?

excel vba
1个回答
0
投票

您不需要 VBA 来完成这项任务,在我看来,这似乎是一种相当老式的做事方式。使用新版本的 Excel,您可以使用更快且更易于维护的公式获得相同的结果。 要获得与当前 VBA 代码相同的结果,您可以使用类似的内容(无疑可以进一步简化):

enter image description here

=LET(
    data, B2:B11,
    names, A2:A11,
    extractDigits, LAMBDA(cell, IFERROR(VALUE(TEXTJOIN("", TRUE, IFERROR(MID(cell, SEQUENCE(LEN(cell)), 1) + 0, ""))), 0)),
    digits, MAP(data, extractDigits),
    uniqueNames, UNIQUE(names),
    maxValues, MAP(uniqueNames, LAMBDA(name, MAX(FILTER(digits, names=name)))),
    HSTACK(uniqueNames, maxValues)
) 

如果您需要在输出中过滤/搜索,可以使用

FILTER
函数来实现。

© www.soinside.com 2019 - 2024. All rights reserved.