获取Excel行索引

时间:2012-04-10 11:14:39

标签: excel vba excel-vba

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

我想用VBA做到这一点。

1 个答案:

答案 0 :(得分:2)

假设货币对在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评论之后,一个更简单的解决方案就是(假设数据只出现在一列中):

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