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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With