Brian
Brian

Reputation: 11

Excel/VBA Basic Function Problem

I know this is a total noob question, but can anyone tell me why this function always returns 0:

Function Cd(Re As Double)

Select Case Re

    Case Re < 1
        Cd = 24 / Re
    Case 1 < Re < 1000
        Cd = 18 * Re ^ (-0.6)
    Case 1000 < Re
        Cd = 0.44

End Select

End Function

Whenever I call it in the spreadsheet, it always returns 0. For example Cd(5000) = 0, when it should be 0.44. Thanks in advance for the help.

Upvotes: 1

Views: 273

Answers (3)

Marc Thibault
Marc Thibault

Reputation: 1728

One simple change (other than the '< x <' ). Make it

Select Case True

Upvotes: 0

GSerg
GSerg

Reputation: 78190

Case Re < 1

That is not good. You evaluate Re in your Select Case in the first place, and now you are comparing Re to Re < 1. Obviously, you wanted

Case Is < 1

Case 1 < Re < 1000 

That is not good either. There is no < X < operator in VB. This expression evaluates to (1 < (Re < 1000)), which essentially becomes either 1 < False or 1 < True, which is always False. What you meant to write here is:

Case 1 to 1000

Case 1000 < Re

Same problem again. You obviously meant:

Case Is > 1000

Upvotes: 5

mechanical_meat
mechanical_meat

Reputation: 169494

In addition to the things GSerg mentions I think you should also explicitly cast the function to return a double.

I just tested that this works as you expect:

Function Cd(Re As Double) As Double

  Select Case Re

    Case Is < 1
        Cd = 24 / Re
    Case 1 To 1000
        Cd = 18 * Re ^ (-0.6)
    Case Is > 1000
        Cd = 0.44

  End Select

End Function

Upvotes: 4

Related Questions