Eriks
Eriks

Reputation: 1

Excel VBA function error

I write this code in the module:

Public Function first()
If (x + 1 < 0) Or (1 - 2 * Sin(x) < 0) Or Sqr(1 - 2 * Sin(x)) = 0 Then
first = "error"
Else
first = Sqr(x + 1) / Sqr(1 - 2 * Sin(x))
End If
End Function

It gives an error with certain values:

enter image description here

Where is the problem?

Upvotes: 0

Views: 96

Answers (2)

John Coleman
John Coleman

Reputation: 51988

I'm pretty sure that your intention is to evaluate Sin(x) where x is measured in degrees (if for no other reason than that evaluating at radians which are whole numbers other than 0 is quite rare), but the function Sin(x) works with radians. You can use the function Randians() to fix this:

Public Function first(ByVal x As Double) As Double
    x = Application.Radians(x)
    If (x + 1 < 0) Or (1 - 2 * Sin(x) < 0) Or Sqr(1 - 2 * Sin(x)) = 0 Then
        first = "error"
    Else
        first = Sqr(x + 1) / Sqr(1 - 2 * Sin(x))
    End If
End Function

Then, for example, first(7) evaluates to 1.218130941.

Upvotes: 1

user4039065
user4039065

Reputation:

When x is 7, Sin(x) is equal to 0.656986598718789.

When you plug this into the formula 1 - 2 * Sin(x), you get -0.313973197437578.

You cannot take the square root (i.e. Sqr(...)) of a negative number. I would suggest adding Abs(...) as a wrapper to guarantee a positive number but I have no idea what you are ultimately trying to accomplish.

Upvotes: 0

Related Questions