将vba中的全局变量传递给函数

时间:2013-06-17 15:12:24

标签: excel vba pointers excel-vba code-structure

所以我有这么多不同的二维数组,它们包含一个流的不同物理属性(马赫数,温度等)。我需要在excel中绘制这些值并计算不同的平均值。这些数组声明为全局。要做到这一点,我曾经为每个数组编写一个子程序,但这不是一个好方法,因为你应该保持尽可能通用吗?

所以我最终得到的结果是:子程序传递给数组和相应的工作表......

还是使用指针?知道如何用其他更高级的编程语言(C ++,...)解决这个问题也很有趣,因为vba不是我选择的武器,但在这种情况下它是必要的。

错误,“类型不匹配:预期数组或用户定义的类型!”

当我打电话给我时使用:

Call WriteFlowVariable(ws_meridian_velocity, MeridSpeed(), average_MeridSpeed(), area_average_MeridSpeed(), mass_average_MeridSpeed())

这是子程序:

Sub WriteFlowVariable(ws As Worksheet, FlowVariable() As Double, average_FlowVariable() As Double, area_average_FlowVariable(), mass_average_FlowVariable())

Dim i As Integer
Dim j As Integer

Dim sum_v As Double
Dim FlowVariabledeltaA(1000, 300) As Double
Dim FlowVariabledeltaA_added(1000) As Double

Dim FlowVariabledeltaM(1000, 300) As Double
Dim FlowVariabledeltaM_added(1000) As Double

'write titles of the charts
ws.Cells.Clear

For j = 0 To SecNumber - 1
    ws.Cells(1, j + 2).value = (j + 1)
Next j
ws.Cells(1, SecNumber + 2) = "Arithmetic Average"
ws.Cells(1, SecNumber + 3) = "Area Average"

For i = 0 To number_of_axial_positions - 1

    sum_v = 0

    'Write section number
    ws.Cells(i + 2, 1).value = i + 1

    'Write value and calculate arithmetic, mass and area average
    For j = 0 To SecNumber - 1
        ws.Cells(i + 2, j + 2).value = FlowVariable(i, j)
        sum_v = sum_v + FlowVariable(i, j)

        If j < SecNumber - 1 Then

            FlowVariable(i, j) = FlowVariable(i, j) * deltaA(i, j)

            FlowVariabledeltaA_added(i) = FlowVariabledeltaA_added(i) + FlowVariabledeltaA(i, j)

            FlowVariabledeltaM(i, j) = FlowVariable(i, j) * deltaM(i, j)

            FlowVariabledeltaM_added(i) = FlowVariabledeltaM_added(i) + FlowVariabledeltaM(i, j)

        End If

    Next j

    average_FlowVariable(i) = sum_v / SecNumber
    'Write arithmetic average to the third last column
    ws.Cells(i + 2, SecNumber + 2) = average_FlowVariable(i)

    area_average_FlowVariable(i) = FlowVariabledeltaA_added(i) / crosssectionareaInput(i)
    'Write area average to the second last column
    ws.Cells(i + 2, SecNumber + 3) = area_average_FlowVariable(i)

    mass_average_FlowVariable(i) = FlowVariabledeltaM_added(i) / crosssectionareaInput(i)
    'Write mass average to the last column
    ws.Cells(i + 2, SecNumber + 4) = mass_average_FlowVariable(i)
Next i

End Sub

1 个答案:

答案 0 :(得分:0)

我根本没有仔细检查你的Sub,而是假设

FlowVariable(,) As Double
average_FlowVariable(,) As Double
area_average_FlowVariable(,)
mass_average_FlowVariable(,)

都被正确地声明为全局变量,您的调用应如下所示:

Call WriteFlowVariable(ws_meridian_velocity, MeridSpeed, average_MeridSpeed, area_average_MeridSpeed, mass_average_MeridSpeed)

...换句话说,请删除()

此外,由于这些是二维数组,因此您的Sub应如下所示:

Sub WriteFlowVariable(ws As Worksheet, FlowVariable(,) As Double, average_FlowVariable(,) As Double, area_average_FlowVariable(,), mass_average_FlowVariable(,))Dim i As Integer

希望这可以解决问题,否则,知道,我会仔细看看。