John
John

Reputation: 1947

Recursive sequence in VBA

I want to write a function which has 5 inputs :

enter image description here

which outputs

enter image description here :

Problem seems very simple for me, however I'm dealing with error :

Function Sequence(x_0 As Double, x_1 As Double, a As Double, b As Double, n As Double) As Double
    If n = 0 Then
        x_0
    ElseIf n = 1 Then
        x_1
    Else
        a * Sequence(x_0, x_1, a, b, n-1) + b * Sequence(x_0, x_1, a, b, n-2)
    End If
End Function

And If I want to use my function :

Sequence(1;1;1;1;1)  

I see error :

enter image description here

Do you hany idea what I'm doing wrong ?

Upvotes: 0

Views: 94

Answers (1)

FaneDuru
FaneDuru

Reputation: 42236

  1. In VBA, the function to call parameters must be separated by comma. Like a UDF function you can call it from sheet using the list separator according to regional settings ["=Sequence(1, 1, 1, 1, 1) or Sequence(1; 1; 1; 1; 1)];

  2. If a called function returns something, the way you call it should be in a way to deal with the returned value:

Debug.Print Sequence(1, 1, 1, 1, 1)

Then, try playing with the function parameters.

  1. When there are some conditional function outputs, your function must be configured to return:
Function Sequence(x_0 As Double, x_1 As Double, a As Double, b As Double, n As Double) As Double
    If n = 0 Then
        Sequence = x_0
    ElseIf n = 1 Then
        Sequence = x_1
    Else
        Sequence = a * Sequence(x_0, x_1, a, b, n - 1) + b * Sequence(x_0, x_1, a, b, n - 2)
    End If
End Function

Upvotes: 1

Related Questions