Search code examples
vbaexcelfor-loopudf

For Loop running error


This code doesn't find the correct output

for say n= 1 (although it gives the correct output for say n= 2,3,4..etc.)

if we put n= 1 to find x then the i loop will continue from 1 to 0, hence the first term in x should vanish and leftover should be the second term 5; but it gives 0 ?

Is there any limitation on the input n to run the for loop ?I would appreciate any help.

 Function math(n As Integer) As Double

 Dim i As Integer
 Dim x As Double

 For i = 1 To n - 1
    x = (n - 1) * 2 + 5
    sum = sum + x
 Next i
 math = sum
 End Function

Solution

  • In the for loop, if you don't precise the Step, the variable will only increment by 1.

    And here, you start at 1 to go to 0, so the loop won't execute, you need to test n to cover both cases :

    Function math(n As Integer) As Double
    If n < 0 Then Exit Function
    Dim i As Integer
    Dim x As Double
    Dim Summ As Double
    
    Select Case n
        Case Is > 1
            For i = 1 To n - 1
               x = (i - 1) * 2 + 5
               Summ = Summ + x
            Next i
        Case Is = 1
            Summ = (n - 1) * 2 + 5
        Case Is = 0
            Summ = 5
        Case Else
            MsgBox "This case is not supported", vbInformation + vbOKOnly
            Exit Function
    End Select
    
    math = Summ
    End Function