【问题标题】:Passing information between sub in VBA在 VBA 中的子之间传递信息
【发布时间】:2015-09-17 23:27:38
【问题描述】:

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

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

【问题讨论】:

    标签: arrays excel call vba


    【解决方案1】:

    问题是您在两个过程中声明了具有相同名称的局部变量,并且期望它们是相同的变量。例如,你在SampleStats 中使用了变量minVal,但你从来没有给它一个值。您在ComputeStatistics 中声明了一个具有相同名称的单独变量这一事实无关紧要。

    将您的代码组合成一个过程,因为它是一个逻辑块。这样您就不必担心来回传递值了。

    一旦你开始工作,如果你仍然想排除ComputeStatistics 部分,请传入你想要更新的所有变量(例如 minVal、maxVal、rang 等)并且不要在ComputeStatistics 程序。

    【讨论】:

      猜你喜欢
      • 2015-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-02
      • 1970-01-01
      • 2022-01-01
      相关资源
      最近更新 更多