I've created a user defined function (UDF) to interpolate (both linear and bilinear). It's just, I keep getting this annoying error that says "A value used in the formula is of the wrong data type." But here's the kicker...I converted the UDF into a subroutine for trouble shooting, and I was able to step through the entire code and get the correct output. I'm stumped, any suggestions? Below is my code.
Function itcinter(efpd As Single, pwr As Single) As Variant
Dim rnge, mtrnge As Range
Dim w, x, y, z, xx, yy, b As Single
Dim scenario, a As Integer
Dim J As Variant
scenario = Worksheets("Input").Range("B1").Value
pwr = pwr / 100#
If (scenario = 1) Then
Worksheets("ITC").Select
'Make table into a range for VLookUp
Set rnge = Worksheets("ITC").Range("A3", [A3].End(xlDown).End(xlToRight))
Set mtrnge = Worksheets("ITC").Range("A3", [A3].End(xlDown))
'If the given value does not match a table value exactly
On Error Resume Next
J = Application.WorksheetFunction.VLookup(efpd, rnge, 1, False)
If Err.Number = 1004 Then
w = Application.WorksheetFunction.VLookup(efpd, rnge, 1, True)
x = Application.WorksheetFunction.VLookup(efpd, rnge, 2, True)
y = Application.WorksheetFunction.VLookup(efpd, rnge, 3, True)
'If the given value is greater than, or equal to the largest table value
If (w = Range("A3").End(xlDown).Value) Then
itcinter = x + pwr * (y - x)
Else
'If the given value requires a table interpolation
a = Application.WorksheetFunction.Match(efpd, mtrnge, 1)
z = Range("A" & a + 3).Value
xx = Range("B" & a + 3).Value
yy = Range("C" & a + 3).Value
b = (z - w)
itcinter = (x / b) * (z - efpd) * (1 - pwr) + _
(xx / b) * (efpd - w) * (1 - pwr) + _
(y / b) * (z - efpd) * (pwr - 0) + _
(yy / b) * (efpd - w) * (pwr - 0)
End If
'If the given value does match a table value exactly
ElseIf (Application.WorksheetFunction.VLookup(efpd, rnge, 1, False) >= 0) Then
a = Application.WorksheetFunction.Match(efpd, mtrnge, 0)
x = Range("B" & a + 2).Value
y = Range("C" & a + 2).Value
itcinter = x + pwr * (y - x)
'Only scenario left is an error
Else
itcinter = "error"
End If
End If
End Function
Bookmarks