VBA 有 ATan2 功能吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5117265/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 11:10:29  来源:igfitidea点击:

Does VBA have an ATan2 function?

vba

提问by Iain Sproat

I'd like to calculate atan2in 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.

我想atan2在 VBA 中进行计算,但我不确定该函数是否存在(甚至不确定在哪里可以找到内置 VBA 函数的规范列表)。我没有使用 Excel,因此无法调用工作表。

I could implementatan2myself, but I'd prefer to avoid doing that if possible.

我可以自己实现atan2,但如果可能的话,我宁愿避免这样做。

采纳答案by Simon Mourier

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

回答by Fionnuala

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.

或者使用对象浏览器。您会发现 Atn 和 Tan 等,但列表很短,不包括 ATan2。

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

如果要添加对 Excel 库的引用,可以使用:

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.

编辑:您可以从任何允许您添加对 Excel 库的引用的 Office 应用程序调用 Excel 工作表函数。这并不意味着使用 Excel 或工作表,而只是使用函数。

回答by Avi

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:

正如 MarkJ 之前指出的,当 X < 0 且 y=0 时,上述代码将失败。我相信以下内容将始终有效:

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.

在 x 和 y 都为 0 的情况下,它利用了 Sgn(0) 返回 0 的优势。

回答by J?cker

You can try with

你可以试试

Application.Atan2