Excel VBA:是否可以使用自定义方法创建自定义函数?

MrM*_*ict 2 methods excel vba function excel-vba

我所指的是,例如,你如何做:

Range().Select
Run Code Online (Sandbox Code Playgroud)

其中"Range()"是函数,"Select"是方法.

例如,如果我有一个函数,我想采用三个代表三角形边长的双精度,并吐出任意一个弧度的最大角度.

Public Function getAngle(a as Double, b as Double, c as Double)

    .degrees = 'some equation to determine degrees as a double
    .rads = 'some equation to determine radians as a string

End Function
Run Code Online (Sandbox Code Playgroud)

因此,您将获得以下结果:

getAngle(3,4,5).degrees:90.0

getAngle(3,4,5).rads:"0.5π"

cyb*_*shu 5

创建一个类,对于这个例子,命名为clsTrig.

Option Explicit

'/ Class  Name : clsTrig

Private m_ddegrees   As Double
Private m_drads  As Double

Public Property Get degrees() As Double
    degrees = m_ddegrees
End Property

Public Property Let degrees(val As Double)
     m_ddegrees = val
End Property

Public Property Get rads() As Double
    rads = m_drads
End Property

Public Property Let rads(val As Double)
     m_drads = val
End Property


Public Function doCalc(a1 As Double, a2 As Double) As Double

    '/ You do the math here. This is just a sample and not actual trigonometery

    m_ddegrees = a1 + a2
    m_drads = a1 - a2


End Function
Run Code Online (Sandbox Code Playgroud)

然后在标准模块中,您将获得所需的行为,如下所示:

Public Function getAngle(a As Double, b As Double) As clsTrig
    Dim oTrig As New clsTrig

    Call oTrig.doCalc(a, b)
    Set getAngle = oTrig
End Function

Sub test()
    MsgBox getAngle(30, 20).degrees
    MsgBox getAngle(30, 20).rads
End Sub
Run Code Online (Sandbox Code Playgroud)