Skip to content

Instantly share code, notes, and snippets.

@pyRobShrk
Created November 30, 2017 23:58
Show Gist options
  • Save pyRobShrk/6016a0e63b90de1013633e6f9e4955e1 to your computer and use it in GitHub Desktop.
Save pyRobShrk/6016a0e63b90de1013633e6f9e4955e1 to your computer and use it in GitHub Desktop.
Excel UDF for bilinear interpolation
Function Int2d(rowLookup As Double, colLookup As Double, lookupRange As Range) As Double
'This function performs 2 dimensional linear interpolation using built-in linear functions
'Lookup range includes column and row lookup values
Dim Row, col As Integer
Dim RowVals, ColVals, lookup As Variant
Dim sl1, sl2, sl3, int1, int2, int3, col1, col2 As Double
Row = 1
col = Row
On Error Resume Next
Row = WorksheetFunction.Match(rowLookup, lookupRange.Offset(1, 0).Columns(1), 1)
col = WorksheetFunction.Match(colLookup, lookupRange.Offset(0, 1).Rows(1), 1)
RowVals = lookupRange.Offset(Row, 0).Columns(1).Resize(2, 1).Value
ColVals = lookupRange.Offset(0, col).Rows(1).Resize(1, 2).Value
lookup = lookupRange.Offset(Row, col).Resize(2, 2).Value
sl1 = WorksheetFunction.Slope(Array(lookup(1, 1), lookup(1, 2)), Array(ColVals(1, 1), ColVals(1, 2)))
sl2 = WorksheetFunction.Slope(Array(lookup(2, 1), lookup(2, 2)), Array(ColVals(1, 1), ColVals(1, 2)))
int1 = WorksheetFunction.Intercept(Array(lookup(1, 1), lookup(1, 2)), Array(ColVals(1, 1), ColVals(1, 2)))
int2 = WorksheetFunction.Intercept(Array(lookup(2, 1), lookup(2, 2)), Array(ColVals(1, 1), ColVals(1, 2)))
col1 = colLookup * sl1 + int1
col2 = colLookup * sl2 + int2
sl3 = WorksheetFunction.Slope(Array(col1, col2), Array(RowVals(1, 1), RowVals(2, 1)))
int3 = WorksheetFunction.Intercept(Array(col1, col2), Array(RowVals(1, 1), RowVals(2, 1)))
Int2d = rowLookup * sl3 + int3
End Function
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment