【发布时间】:2010-09-21 15:19:08
【问题描述】:
给定
一个搜索键
---------------------------
| | A | B | C | D |
---------------------------
| 1 | 01 | 2 | 4 | TextA |
---------------------------
Excel 表格
------------------------------
| | A | B | C | D | E |
------------------------------
| 1 | 03 | 5 | C | TextZ | |
------------------------------
| 2 | 01 | 2 | 4 | TextN | |
------------------------------
| 3 | 01 | 2 | 4 | TextA | |
------------------------------
| 4 | 22 | T | N | TextX | |
------------------------------
问题
我想要一个这样的函数:f(key) -> result_row.
这意味着:给定一个搜索键 (01, 2, 4, TextA),该函数应该告诉我在上面的示例中匹配的行是 3。
搜索键(A、B、C、D)中的值是唯一标识符。
如何获取匹配行的行号?
一个解决方案
我首先想到的解决方案是使用 Visual Basic for Application (VBA) 在 A 列中扫描“01”。找到包含“01”的单元格后,我会检查 B、C 和 D 列中的相邻单元格是否符合我的搜索条件。
我猜这个算法会起作用。但是:有更好的解决方案吗?
版本
- Excel 2000 9.0.8961 SP3
- VBA 6.5
但是,如果您碰巧知道任何更高版本的 Excel 或 VBA 中的解决方案,我也很想知道。
编辑:22.09.2010
谢谢大家的回答。 @MikeD:非常好的功能,谢谢!
我的解决方案
这是我原型化的解决方案。这都是硬编码的,太冗长了,不像 MikeD 的解决方案那样是一个函数。但我会在我的实际应用程序中重写它以获取参数并返回结果值。
Sub FindMatchingRow()
Dim searchKeyD As Variant
Dim searchKeyE As Variant
Dim searchKeyF As Variant
Dim searchKeyG As Variant
Const indexStartOfRange As String = "D6"
Const indexEndOfRange As String = "D9"
' Initialize search key
searchKeyD = Range("D2").Value
searchKeyE = Range("E2").Value
searchKeyF = Range("F2").Value
searchKeyG = Range("G2").Value
' Initialize search range
myRange = indexStartOfRange + ":" + indexEndOfRange
' Iterate over given Excel range
For Each myCell In Range(myRange)
foundValueInD = myCell.Offset(0, 0).Value
foundValueInE = myCell.Offset(0, 1).Value
foundValueInF = myCell.Offset(0, 2).Value
foundValueInG = myCell.Offset(0, 3).Value
isUnitMatching = (searchKeyD = foundValueInD)
isGroupMatching = (searchKeyE = foundValueInE)
isPortionMatching = (searchKeyF = foundValueInF)
isDesignationMatching = (searchKeyG = foundValueInG)
isRowMatching = isUnitMatching And isGroupMatching And isPortionMatching And isDesignationMatching
If (isRowMatching) Then
Range("D21").Value = myCell.Row
Exit For
End If
Next myCell
End Sub
这是与上述代码一起使用的 Excel 表格:
【问题讨论】: