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 usi
As pointed out by MarkJ earlier, the above code 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.
You can try with
Application.Atan2
Maybe this code would suit you:
Private Const Pi As Double = 3.14159265358979
Public Function Atn2(y As Double, x As Double) As Double
If x > 0 Then
Atn2 = Atn(y / x)
ElseIf x < 0 Then
Atn2 = Sgn(y) * (Pi - Atn(Abs(y / x)))
ElseIf y = 0 Then
Atn2 = 0
Else
Atn2 = Sgn(y) * Pi / 2
End If
End Function