У меня была похожая проблема с поиском «самого последнего обменного курса» через VBA.Это мой код, может быть, он может вдохновить вас ...
Function GetXRate(CurCode As Variant, Optional CurDate As Variant) As Variant
Dim Rates As Range, chkDate As Date
Dim Idx As Integer
GetXRate = CVErr(xlErrNA) ' set to N/A error upfront
If VarType(CurCode) <> vbString Then Exit Function ' if we didn't get a string, we terminate
If IsMissing(CurDate) Then CurDate = Now() ' if date arg not provided, we take today
If VarType(CurDate) <> vbDate Then Exit Function ' if date arg provided but not a date format, we terminate
Set Rates = Range("Currency") ' XRate table top-left is a named range
Idx = 2 ' 1st row is header row
' columns: 1=CurCode, 2=Date, 3=XRate
Do While Rates(Idx, 1) <> ""
If Rates(Idx, 1) = CurCode Then
If Rates(Idx, 2) = "" Then
GetXRate = Rates(Idx, 3) ' rate without date is taken at once
Exit Do
ElseIf Rates(Idx, 2) > chkDate And Rates(Idx, 2) <= CurDate Then
GetXRate = Rates(Idx, 3) ' get rate but keep searching for more recent rates
chkDate = Rates(Idx, 2) ' remember validity date
End If
End If
Idx = Idx + 1
Loop
End Function
Это скорее классическая конструкция цикла с индексом цикла (Idx as Integer
) и двумя критериями выхода, поэтому мне не нужно идтив всех строках при всех обстоятельствах.