excelvbaif-statementudf

If then Else Excel VBA - "End If" needed?


so I m writing a UDF in Excel vba of the kind:

function ... if ... then ... else for i... to ... equations ... next i * end function

Now I noticed, that the function seems to work just fine, however I was wondering whether I shouldnt be using an "end if" at the position of (*) in the code? If I do, I receive an error msg stating there was no if corresponding IF to that "end if" block, though!? So in general, isn't there a Need for an "end if" in if then else constructions ? Thanks in advance!

/edit: 'if ... then ... else' is a one liner. However the else block does contain multiple lines and in particular a loop...


Solution

  • If you put IF THEN ELSE in one line, then the if condition ends on that line and next line will be executed no matter what.

    For example,

    If true then x =1 else x = 2
    y = 1
    

    this case

    if true, x will be 1 and y will be 1

    if false, x will be 2 and y will be 1


    if true then
        x = 1
    else
        x = 2
        y = 1
    end if
    

    this case,

    if true, x will be 1 and y will be empty

    if false, x will be 2 and y will be 1


    In addition, if you do

    If true then x = 1 else 
    x = 2
    

    x will always be 2 no matter true or false