我试图教自己VBA写一些小东西。我尝试制作一些允许您选择一些数据然后计算均值和方差的东西。我的代码如下:
Sub VarianceCalculator()
Dim k As Integer
Dim SelectedData As Range
Dim SelectedDataArray() As Variant
Dim Var As Double
Dim Mu As Double
On Error Resume Next
Set SelectedData = Application.InputBox("Select a range of data to be
calculated", Default:=Selection.Address, Type:=8)
On Error GoTo 0
SelectedDataArray = Range(SelectedData.Address)
k = UBound(SelectedDataArray)
Call VarianceCalculatorWithArray(SelectedDataArray, k)
MsgBox ("The selected data has variance " & Var & " and has mean " & Mu)
End Sub
Sub VarianceCalculatorWithArray(Data() As Variant, k As Integer)
Dim Var As Double
Dim Mu As Double
Dim j As Integer
Dim i As Integer
ReDim Data(k) As Variant
Mu = 0
Var = 0
For j = 0 To k
Mu = Mu + (Data(j)) / (k + 1)
Next j
For i = 0 To k
Var = Var + ((Data(i) - Mu) ^ (2)) / (k + 1)
Next i
End Sub
我认为错误是数据不会被转移到数组中,但我无法找到解决方案。
谢谢!
答案 0 :(得分:0)
有两个主要问题:
(1)如果要将变量Var
和Mu
从一个过程传递到另一个过程,则必须在第一个过程之前将它们声明为公共变量。另一种方法是将VarianceCalculatorWithArray
设置为函数。
(2)数组Data()
是2D,因为范围由行和列组成。因此,如果您想使用此数组中的元素,则必须将其作为Data(1, 1)
来处理。另请注意,此范围数组以第1行和第1列开头。因此,for...next
语句应以1开头而不是0开始。
请注意,您始终可以设置断点以检查数据是否已传输到阵列中。