Hi,
i have written a code in VBA to interpolate the value of Y0 corresponding to X0 using a set of (X,Y) points. (I have written this in module1) . This function works when i call it through a Sub or another Function in VBA. but it does not work when I try to use it as a function in my excel worksheets (when I type : =interpolate(A1:A10,B1:B10,30) .... 30 is an arbitrary value). in this case I get #value! error
The function is known in within the worksheets because when I start typing its name, the Auto Name Complete feature of excel, finds this function.
I am new to VAB for excel. Please give me a hint to see my mistakes of if something is missing inside my code.
The code is :
PHP Code:
Public Function Interpolate(ByRef X() As Double, ByRef Y() As Double, ByRef X0 As Double) As Double
Dim I As Integer, Slope As Double, NData As Integer
NData = UBound(X)
For I = 1 To UBound(X) - 1
If (X(I) = X0) Then
Interpolate = Y(I)
Exit Function
ElseIf (X0 < ListMax(X(I), X(I + 1)) And X0 > ListMin(X(I), X(I + 1))) Then
Slope = (Y(I) - Y(I + 1)) / (X(I) - X(I + 1))
Interpolate = Y(I + 1) + Slope * (X0 - X(I + 1))
Exit Function
End If
Next I
End Function
Public Function ListMax(ParamArray ListItems() As Variant)
Dim I As Integer
ListMax = ListItems(0)
For I = 0 To UBound(ListItems())
If ListItems(I) > ListMax Then ListMax = ListItems(I)
Next I
End Function
Public Function ListMin(ParamArray ListItems() As Variant)
Dim I As Integer
ListMin = ListItems(0)
For I = 0 To UBound(ListItems())
If ListItems(I) < ListMin Then ListMin = ListItems(I)
Next I
End Function
I appreciate your help. Thanks
Bookmarks