Does VBA have an ATan2 feature?

I would like to calculate atan2in VBA, but I'm not sure if this function exists (or even where to find the canonical list of VBA built-in functions). I do not use Excel, so calling a worksheet is not possible.

I could implement it atan2 myself, but I would prefer not to, if possible.

+3
source share
4 answers

Perhaps this code will 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
+2
source

To get a list, enter in your module

VBA.Math

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

If you want to add a link to the Excel library, you can use:

Excel.WorksheetFunction.Atan2

EDIT: Excel Office, Excel. Excel , .

+6

As MarkJ mentioned earlier, the above code will not work when X <0 and y = 0. I believe that 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

We use Sgn (0), which returns 0 if both x and y are 0.

+4
source

You can try with

Application.Atan2
0
source

Source: https://habr.com/ru/post/1794704/


All Articles