简体   繁体   中英

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+dt Sn) Q(t,Tj)]/[Z(t,Tn) (L+dt*Sn)] +(Q(t,Tn-1) L)/(L+dt Sn)

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

Take the habit to format and increment your code, especially before posting it!


  1. You need to type the output of the function (on the line of the function name)
  2. A parenthesis is missing from the line P = Z(j) * (L*Q(j-1)-(L+ dt * a(n) * Q(j))
  3. n is empty (and so are a , b and Q ) when you try to redim your arrays, so you need to define them!
  4. Z(j) will also give you an error, because it is a Range, you need Z.Cells(i,j)

Try this :

Function Bootstrap(S As Range, Z As Range, L As Double) 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

n = Application.WorksheetFunction.Max(S.Columns.count, Z.Columns.count)
a = S.Value
b = Z.Value
dt = 1
sum = 0
ReDim Q(1 To n)
Q(0) = 0
'Q(1) = "??"


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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM