在一个函数或子例程中定义多个VBA对象?

时间:2012-09-05 05:46:19

标签: vba excel-vba excel

我有以下VBA代码:

Option Explicit

Private a(2) as Double
Private b(2) as Double

Public Function Hello(X1 As Double, X2 As Double) As Double

    a(1) = X1 + X2
    a(2) = X1/X2
    b(1) = X1
    b(2) = X2^2

Hello = a(1)+a(2)+b(1)+b(2)

End Function

Hello函数中,我定义了a(1)a(2)b(1)b(2)

但是,我想创建一些接受X1X2作为参数的函数或子例程,并吐出a(1)a(2),{{的值1}},b(1)。这是因为我在我的模块中的大约20个函数中对b(2)a(1)a(2)b(1)使用了上述定义,并且希望避免在以下方面执行以下操作:我使用论文的每个功能:

b(2)

2 个答案:

答案 0 :(得分:1)

我会用类对象和属性/方法来构造它。请在Class1

中尝试此操作
Option Explicit

Private a(2) As Double, b(2) As Double

Public Sub Initialize(ByVal x1 As Double, ByVal x2 As Double)
    a(1) = x1 + x2
    a(2) = x1 / x2
    b(1) = x1
    b(2) = x2 ^ 2
End Sub

Public Property Get Hello() As Double
    Hello = a(1) + a(2) + b(1) + b(2)
End Property

Public Property Get Goodbye() As Double
    Goodbye = a(1) - a(2) + b(1) - b(2)
End Property

Public Function BusyWork(ByVal t As Double) As Double
    Dim i As Integer, x As Double
    x = 0#
    For i = 1 To 2
        x = x + (a(i) - t) * (b(i) - t)
    Next i
    BusyWork = Sqr(x)
End Function

然后在模块中使用它

Public Sub UseClass()
    Dim c As New Class1

    c.Initialize 10.6, -4#

    Debug.Print c.Hello
    Debug.Print c.Goodbye
    Debug.Print c.BusyWork(-1#)
End Sub

您可以在此处阅读有关VBA课程的更多信息:

答案 1 :(得分:0)

如果只是从不同的函数为数组赋值,那么你可以创建一个通用的过程并从所有函数中调用它们。见这个例子

Option Explicit

Dim a(2) As Double, b(2) As Double
Dim Hello As Double

Function FOne()
    '
    '~~> Rest of the code
    '      
    Sample 1,2
End Function

Function FTwo()
    '
    '~~> Rest of the code
    '      
    Sample 2,3
End Function   
'
'~~> Rest of the functions
'   
Function FTwenty()
    '
    '~~> Rest of the code
    '     
    Sample 3.2 ,4.2
End Function

Sub Sample(X1 As Double, X2 As Double)
    a(1) = X1 + X2: a(2) = X1 / X2
    b(1) = X1: b(2) = X2 ^ 2

    Hello = a(1) + a(2) + b(1) + b(2)
End Sub