【发布时间】:2015-10-30 20:15:47
【问题描述】:
我有一个大型数据表,我想根据 3 组条件在 VBA 中进行搜索。可以假定每个行条目是唯一的。表格/数据本身的格式不能因要求而改变。 (我看过几篇关于相关问题的帖子,但还没有找到可行的解决方案。)
一开始我在循环中使用了经典的VBA find 方法:
Set foundItem = itemRange.Find(What:=itemName, Lookin:=xlValues, lookat:=xlWhole, SearchOrder:=xlByRows)
If Not foundItem Is Nothing Then
firstMatchAddr = foundItem.Address
Do
' *Check the other fields in this row for a match and exit if found*
Set foundItem = itemRange.FindNext(foundItem)
Loop While foundItem.Address <> firstMatchAddr And Not foundItem Is Nothing
End If
但是因为这需要在大量数据上调用多次,所以速度并不好。
我做了一些搜索,发现我可以将match 方法与index 一起使用。所以我尝试了很多变体都没有成功,例如:
result = Evaluate("=MATCH(1, (""" & criteria1Name & """=A2:A" & lastRow & ")*(""" & criteria2Name & """=B2:B" & lastRow & ")*(""" & criteria3Name & """=C2:C" & lastRow & "), 0)")
和
result = Application.WorksheetFunction.Index(resultRange, Application.WorksheetFunction.Match((criteria1Name = criteria1Range)*(criteria2Name = criteria2Range)*(criteria3Name = criteria3Range))
和
result = Application.WorksheetFunction.Index(resultRange, Application.WorksheetFunction.Match((criteria1Range=criteria1Name )*(criteria2Range=criteria2Name )*(criteria3Range=criteria3Name ))
然后我尝试使用AutoFilter 进行排序:
.Range(.Cells(1,1), .Cells(lastRow, lastCol)).AutoFilter Field:=1, Criteria1:="=" & criteria1Name
.Range(.Cells(1,1), .Cells(lastRow, lastCol)).AutoFilter Field:=2, Criteria1:="=" & criteria2Name
.Range(.Cells(1,1), .Cells(lastRow, lastCol)).AutoFilter Field:=3, Criteria1:="=" & criteria3Name
但是因为其中一个排序列包含日期,所以我无法让 AutoFilter 正常工作。
我的问题是,如何在 Excel VBA 中根据多个条件搜索列,不循环,返回行号或我在该行的单元格中的值有兴趣?
【问题讨论】:
-
你为什么反对循环播放?你在说多少行?
-
你想对返回的结果做什么?