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

时间:2016-08-26 16:55:09

标签: excel vba function excel-vba methods

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

Range().Select

其中“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

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

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

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

2 个答案:

答案 0 :(得分:5)

创建一个类,对于此示例名称为clsTrig。

fit_L

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

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

答案 1 :(得分:1)

使用类型:

Option Explicit

Type cType
    Degrees As Double
    rads As Double
End Type


Sub tester()

    Dim a As cType

    a = getAngle(1, 2, 3)

    Debug.Print a.Degrees, a.rads

End Sub


Public Function getAngle(a As Double, b As Double, c As Double) As cType
Dim rv As cType

    rv.Degrees = 88  'for example
    rv.rads = 99     'for example

    getAngle = rv

End Function