1

我有以下 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), b(1),的值b(2)a(1)这是因为我在模块中的大约 20 个函数中使用了, a(2), b(1),的上述定义,b(2)并且希望避免在我使用论文的每个函数中执行以下操作:

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

2 回答 2

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 类的更多信息:

于 2012-09-05T13:08:01.810 回答
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
于 2012-09-05T07:56:58.237 回答