Search code examples
vbaexcelsyntax-errorudf

Excel VBA #Value! Error


I have the following function that when I run it says #value! error.

I would appreciate any help.

Function Bootstrap(S As Object, Z As Object, L As Double)

    Dim j As Integer
    Dim a() As Double
    Dim b() As Double
    Dim n As Integer
    Dim Q() As Double
    Dim sum As Double
    Dim P As Double

    ReDim a(1 To n)
    ReDim b(1 To n)
    ReDim Q(1 To n)

    dt = 1
    sum = 0
    Q(0) = 0

    For j = 1 To n - 1
        S.Cells(j, 1).Value = a(j)
        Z.Cells(j, 2).Value = b(j)
        P = Z(j) * (L * Q(j-1) - (L + dt * a(n) * Q(j))
        sum = sum + P
    Next j

    Bootstrap = sum

End Function

Bootstrapping function calculates the following value In fact I am trying to calculate this formula Q(t,Tn)=(∑(j=1)to(n-1) Z(t,Tj)[LQ(t,Tj-1)-(L+dtSn)Q(t,Tj)]/[Z(t,Tn)(L+dt*Sn)] +(Q(t,Tn-1)L)/(L+dtSn)

Inputs given are[S1 ,S2,….Sn ],[Z(t,T1),Z(t,T2)…..Z(t,Tn)]and and L=0.4


Solution

  • Try this code : entered as =Bootstrap(A1:B1,A2:B2,0.4)
    I have corrected the following
    - Assigning the ranges to variants
    - defining dt as double
    - Dim Q() as 0 to n
    - using A() and b() in the formula
    - the input ranges are rows not columns

    Function Bootstrap(S As Range, Z As Range, L As Double) As Double
    Dim j As Integer
    Dim a As Variant
    Dim b As Variant
    Dim n As Integer
    Dim Q() As Double
    Dim sum As Double
    Dim P As Double
    Dim dt As Double
    
    n = Application.WorksheetFunction.Max(S.Columns.Count, Z.Columns.Count)
    a = S.Value
    b = Z.Value
    dt = 1
    sum = 0
    ReDim Q(0 To n)
    Q(0) = 0
    
    For j = 1 To n - 1
        P = b(1, j) * (L * Q(j - 1)) - (L + dt * a(1, j) * Q(j - 1))
        sum = sum + P
        Q(j) = sum
    Next j
    
    Bootstrap = sum
    End Function