USD/XYZ
1 つの列に通貨ペアやなどを含む Excel スプレッドシートがありXYZ/USD
ます。セルの行番号を知りたいUSD/ABC
(仮定)。USD
また、最初の 3 文字が含まれている行と含まれていない行を知りたいです。
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 コメントに続いて、さらに単純な解決策は次のようになります (データが 1 つの列にのみ表示されると仮定します)。
Function findCurrencyPair(pair As String) As Long
On Error Resume Next
findCurrencyPair = Sheets("SpotRates").Cells.Find(What:=pair).Row
End Function