在VBA中传递信息

时间:2015-07-01 00:14:18

标签: arrays excel-vba call vba excel

我正在尝试从一个子数组到另一个子数组,以便它可以用于计算。计算完成后,我需要将它们发送回第一个子程序。这是我的代码,当我运行它时,绝对没有任何反应。

Public Sub SampleStats()
Option Explicit

Dim n As Integer        ' sample size
Dim x() As Double       ' array containing x values
Dim i As Integer        ' loop counter
Dim rang As Double

' variables to hold output from computation subroutines
Dim minVal As Double        ' minimim value
Dim maxVal As Double        ' maximum value
Dim mean As Double          ' mean value
Dim var As Double           ' variance
Dim stdDev As Double        ' standard deviation

' get sample size
Sheets("Q1_Stats").Select
Range("B8").Select
n = ActiveCell.Value

' create an array
ReDim x(n - 1)            ' redimension x now that we know how many values we have

' get x values
Range("B11").Select
For i = 0 To n - 1
    x(i) = ActiveCell.Offset(i)
Next i

' Call subroutine to compute statistics
 ' *** put your call statemenAst below (with arguments)
Call ComputeStatistics(x(), n)

 ' Call ComputeStatistics(ByVal ..., ByRef ..., ... )

' now output results
Range("F9").Select
ActiveCell.Offset(0).Value = minVal

Range("F10").Select
ActiveCell.Offset(0).Value = maxVal

Range("F11").Select
ActiveCell.Offset(0).Value = rang

Range("F12").Select
ActiveCell.Offset(0).Value = mean

Range("F13").Select
ActiveCell.Offset(0).Value = var

Range("F14").Select
ActiveCell.Offset(0).Value = stdDev

End Sub

Sub ComputeStatistics(x() As Double, n As Integer)

Dim rang As Double
Dim maxVal As Single
Dim i As Integer
Dim mean As Single
Dim minVal As Double

i = 0
maxVal = x(0)
For i = 1 To UBound(x)
    If maxVal < x(i) Then
         maxVal = x(i)
    End If
Next i

'Computes mean average
i = 0
mean = x(0)
For i = 1 To UBound(x)
    mean = mean + x(i)
Next i
mean = mean / n

'Computes the lowest value
i = 0
minVal = x(0)
For i = 1 To UBound(x)
    If minVal > x(i) Then
         minVal = x(i)
    End If
Next i

'Calulates Range
rang = maxVal - minVal

end sub

1 个答案:

答案 0 :(得分:2)

问题是您已在两个程序中使用相同的 名称 声明了局部变量,并期望它们是相同的 变量< / EM> 即可。例如,您在minVal中使用变量SampleStats,但您从未给它赋值。您在ComputeStatistics中声明了具有相同名称的单独变量这一事实无关紧要。

将代码合并到一个过程中,因为它无论如何都是一个逻辑块。然后你不必担心来回传递值。

如果您仍然希望将ComputeStatistics部分分解出去,那么一旦您完成了工作,请传入您想要更新的所有变量(例如minVal,maxVal,rang等)并且不要声明它们在ComputeStatistics程序中。