Skip to content

Instantly share code, notes, and snippets.

@strickc
Last active March 3, 2017 03:11
Show Gist options
  • Save strickc/cfef9f465fd65c052b3d0e8a20d7dbda to your computer and use it in GitHub Desktop.
Save strickc/cfef9f465fd65c052b3d0e8a20d7dbda to your computer and use it in GitHub Desktop.
Excel VBA interpolate function
Public Function interpolate(knownValue As Double, knownRange As range, resultRange As range) As Double
Application.Volatile
Dim kR As Variant, uR As Variant, i As Integer, kBottom As Double, kTop As Double, uBottom As Double, uTop As Double, s As Integer
kR = knownRange
uR = resultRange
If (Not UBound(kR) = UBound(uR)) Or UBound(uR) < 2 Then
interpolate = CVErr(xlErrValue)
Exit Function
End If
For i = LBound(kR) To UBound(kR)
If knownValue <= kR(i, 1) Or i = UBound(kR) Then
If i = LBound(kR) Then
i = i + 1
End If
kBottom = kR(i - 1, 1)
kTop = kR(i, 1)
uBottom = uR(i - 1, 1)
uTop = uR(i, 1)
Exit For
End If
Next i
interpolate = (knownValue - kBottom) / (kTop - kBottom) * (uTop - uBottom) + uBottom
End Function
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment