Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does VBA have an ATan2 function?

Tags:

vba

I'd like to calculate atan2 in VBA, but I'm not sure if that function exists (or even where to find a canonical list of built-in VBA functions). I'm not using Excel so a worksheet call isn't possible.

I could implement atan2 myself, but I'd prefer to avoid doing that if possible.

like image 401
Iain Sproat Avatar asked Dec 04 '22 23:12

Iain Sproat


2 Answers

As pointed out by MarkJ earlier, the accepted answer will fail when X < 0 and y=0. I believe the following will work all the time:

Function ArcTan2(X As Double, Y As Double) As Double

    Private Const PI As Double = 3.14159265358979
    Private Const PI_2 As Double = 1.5707963267949

    Select Case X
        Case Is > 0
            ArcTan2 = Atn(Y / X)
        Case Is < 0
            ArcTan2 = Atn(Y / X) + PI * Sgn(Y)
            If Y = 0 Then ArcTan2 = ArcTan2 + PI
        Case Is = 0
            ArcTan2 = PI_2 * Sgn(Y)
    End Select

End Function

It takes advantage of Sgn(0) returning 0 in the case where both x and y are 0.

like image 163
Avi Avatar answered Dec 20 '22 08:12

Avi


To get a list, type into your module

VBA.Math

Or use the object browser. You will find Atn and Tan, amongst others, but the list is quite short and ATan2 is not included.

If you wish to add a reference to an Excel library, you can use:

Excel.WorksheetFunction.Atan2

EDIT: You can call Excel worksheet functions from any Office application that allows you to add a reference to the Excel libraries. This does not mean using Excel or a worksheet, just the function.

like image 33
Fionnuala Avatar answered Dec 20 '22 07:12

Fionnuala