获取Excel行索引

我有一个Excel电子表格,在一列中有货币对USD/XYZXYZ/USD等。 我想知道单元格的行号USD/ABC (假设)。 另外,我想知道哪些行有USD作为前三个字符,哪些没有。

我想用VBA来做到这一点。

假设货币对在列A中,则可以使用一个公式:

 =MATCH("USD/EUR",A:A,0) 

它将返回货币所在的行(如果有重复,则返回它首次出现的行)。

如果你想使用VBA,你可以读取一个数组中的数据,并循环访问数组(下面是一个寻找“EUR / USD”的例子,你可以根据需要进行调整):

 Sub test() Dim row As Long row = findCurrencyPair("EUR/USD") If row = 0 Then MsgBox "EUR/USD not found" Else MsgBox "EUR/USD found in row " & row End If End Sub Function findCurrencyPair(pair As String) As Long Dim data As Variant Dim i As Long Dim lastRow As Long With Sheets("SpotRates") lastRow = .Cells.Find(What:="*", after:=.Range("A1"), LookIn:=xlFormulas, _ SearchOrder:=xlByRows, SearchDirection:=xlPrevious).EntireRow.row data = .Range("A1:A" & lastRow) 'Replace A with the relevant column name End With If IsArray(data) = False Then Exit Function 'Empty sheet For i = LBound(data, 1) To UBound(data, 1) If data(i, 1) = pair Then findCurrencyPair = i Exit Function End If Next i 'if not found, returns 0 End Function 

编辑

在@Readify评论之后,更简单的解决scheme是(假设数据只出现在一列中):

 Function findCurrencyPair(pair As String) As Long On Error Resume Next findCurrencyPair = Sheets("SpotRates").Cells.Find(What:=pair).Row End Function