gpt4 book ai didi

vba - 如何根据多个条件获取行?

转载 作者:行者123 更新时间:2023-12-03 02:48:13 28 4
gpt4 key购买 nike

我正在尝试在工作表中搜索前 3 列中的值与一组 3 个条件匹配的行。我正在使用这种线性搜索:

Function findRow(pName as string,fNo as string,mType as string) As Long

Dim rowCtr As Long

rowCtr = 2
While Not rowMatchesCriteria(rowCtr, pName,fNo,mType)
rowCtr = rowCtr + 1
Wend
findRow=rowCtr

End Function



Function rowMatchesCriteria(row As Long, pName As String, fNo As String, mType As String) As Boolean

rowMatchesCriteria = dSheet.Cells(row,1)=pName _
And dSheet.Cells(row,2)=fNo _
And dSheet.Cells(row,3)=mType

End Function

我们可以假设对于任意 3 个条件,只有一个匹配项。然而,这是非常慢的。 dSheet 有约 35,000 个条目可供搜索,我需要执行约 400,000 次搜索。

我查看了 this question 中的一些解决方案,虽然我确信使用自动过滤器或高级功能会比线性搜索更快,但我不明白如何获取过滤器返回的行的索引。我正在寻找的是:

Sub makeUpdate(c1 as string,c2 as string,c3 as string)

Dim result as long

result = findRow(c1,c2,c3)

dSheet.Cells(result,updateColumn) = someUpdateValue

End Sub

应用自动筛选后,如何实际返回我正在查找的结果行?

最佳答案

就性能而言,您很难击败基于字典的查找表:

Sub FindMatches()

Dim d As Object, rw As Range, k, t
Dim arr, arrOut, nR, n

t = Timer

'create the row map (40k rows)
Set d = GetRowLookup(Sheets("Sheet1").Range("A2:C40001"))

Debug.Print Timer - t, "map"
t = Timer

'run lookups on the row map
'(same values I used to create the map, but randomly-sorted)
For Each rw In Sheets("sheet2").Range("A2:C480000").Rows
k = GetKey(rw)
If d.exists(k) Then rw.Cells(3).Offset(0, 1).Value = d(k)
Next rw

Debug.Print Timer - t, "slow version"
t = Timer

'run lookups again - faster version
arr = Sheets("sheet2").Range("A2:C480000").Value
nR = UBound(arr, 1)
ReDim arrOut(1 To nR, 1 To 1)
For n = 1 To nR
k = arr(n, 1) & Chr(0) & arr(n, 2) & Chr(0) & arr(n, 3)
If d.exists(k) Then arrOut(n, 1) = d(k)
Next n
Sheets("sheet2").Range("D2").Resize(nR, 1).Value = arrOut

Debug.Print Timer - t, "fast version"

End Sub


'create a dictionary lookup based on three column values
Function GetRowLookup(rng As Range)
Dim d As Object, k, rw As Range
Set d = CreateObject("scripting.dictionary")
For Each rw In rng.Rows
k = GetKey(rw)
d.Add k, rw.Cells(1).Row 'not checking for duplicates!
Next rw
Set GetRowLookup = d
End Function

'create a key from a given row
Function GetKey(rw As Range)
GetKey = rw.Cells(1).Value & Chr(0) & rw.Cells(2).Value & _
Chr(0) & rw.Cells(3).Value
End Function

关于vba - 如何根据多个条件获取行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23550582/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com