我需要一个VBA中的函数,它根据2 where子句找到行号。
以下是Excel示例:
** A B C D**
1 id1 day1 val1 xxx
2 id2 day1 val2 xxx
3 id3 day1 val3 xxx
4 id1 day2 val1 xxx
5 id2 day2 val2 xxx
6 id3 day2 val3 xxx
我需要找到行号(在这种情况下,行号是 2 ),其中B =“day1”,A =“id2”。
根据行号,我需要进一步获取其他列的值,即C2,D2
希望问题很清楚。
谢谢!
答案 0 :(得分:11)
使用这样的数据设置,您可以使用MATCH函数获取行号:
=MATCH(1,INDEX(($A$1:$A$6="id2")*($B$1:$B$6="day1"),),0)
如果这些条件没有匹配项,公式将返回#N / A错误。您还可以将条件更改为单元格引用,例如:
=MATCH(1,INDEX(($A$1:$A$6=F1)*($B$1:$B$6=G1),),0)
对于问题的第二部分,返回带有找到的行号的值,可以使用INDEX函数从列中返回值。假设匹配公式在单元格H1中,这两个公式将分别从C列和D列返回值:
=INDEX($C$1:$C$6,H1)
=INDEX($D$1:$D$6,H1)
或者,你可以把它全部放在一个公式中:
=INDEX($C$1:$C$6,MATCH(1,INDEX(($A$1:$A$6=F1)*($B$1:$B$6=G1),),0))
如果您不想查看错误,可以在Excel 2007上使用IFERROR
=IFERROR(INDEX($C$1:$C$6,MATCH(1,INDEX(($A$1:$A$6=F1)*($B$1:$B$6=G1),),0)),"No Matches")
检查Excel 2003及以下版本时出错:
=IF(ISNA(MATCH(1,INDEX(($A$1:$A$6=F1)*($B$1:$B$6=G1),),0)),"No Matches",INDEX($C$1:$C$6,MATCH(1,INDEX(($A$1:$A$6=F1)*($B$1:$B$6=G1),),0)))
[编辑]:我按用户请求包含VBA解决方案。这使用了一个非常高效和灵活的find循环,并展示了一旦找到匹配项,如何从其他列中提取值:
Sub tgr()
Dim rngFound As Range
Dim strFirst As String
Dim strID As String
Dim strDay As String
strID = "id2"
strDay = "day1"
Set rngFound = Columns("A").Find(strID, Cells(Rows.Count, "A"), xlValues, xlWhole)
If Not rngFound Is Nothing Then
strFirst = rngFound.Address
Do
If LCase(Cells(rngFound.Row, "B").Text) = LCase(strDay) Then
'Found a match
MsgBox "Found a match at: " & rngFound.Row & Chr(10) & _
"Value in column C: " & Cells(rngFound.Row, "C").Text & Chr(10) & _
"Value in column D: " & Cells(rngFound.Row, "D").Text
End If
Set rngFound = Columns("A").Find(strID, rngFound, xlValues, xlWhole)
Loop While rngFound.Address <> strFirst
End If
Set rngFound = Nothing
End Sub
答案 1 :(得分:1)
在VBA中,您可以执行以下强力检查:
Public Sub Test()
Dim message As String
Dim row As Long
row = Find("id1", "day2")
message = "Not Found"
If (row > 0) Then
message = ActiveSheet.Cells(row, 3).Value
End If
MsgBox message
End Sub
Function Find(aVal As String, bVal As String) As Long
Dim maxRow As Long
Dim row As Long
maxRow = Range("A65536").End(xlUp).row
For row = 2 To maxRow
Dim a As String
a = ActiveSheet.Cells(row, 1).Value
b = ActiveSheet.Cells(row, 2).Value
If a = aVal And b = bVal Then
Find = row
Exit Function
End If
Next row
Find = -1
End Function