计算VBA中数组的差异

我有一个与VBA的麻烦。 我需要计算数组的方差。 但是,在for循环中的数组,如果我使用Next i会增加1我所以我总是要面对来自VBA的错误消息。

这是我的代码:

 Function cal_var(dta As Variant) Dim N, i, j As Integer Dim tre() As Double N = UBound(dta) Dim vec_var() As Integer ReDim vec_var(1 To N) For i = 1 To N j = 1 ReDim tre(1 To i) For j = 1 To i tre(j) = dta(j) Next j vec_var(i) = Application.WorksheetFunction.Var_P(tre) Next i cal_var = vec_var End Function 

以下Sub检查我的function

 Sub test() Dim b(1 To 5) As Integer Dim a As Double b(1) = 1 b(2) = 2 b(3) = 3 b(4) = 4 b(5) = 5 a = cal_var(b) MsgBox a End Sub 

基于任务描述,一个简单的VBA公式将返回数组的方差( b按照您的样本):

 Function cal_var(dta As Variant) cal_var = Application.WorksheetFunction.Var_P(dta) End Function Sub test() Dim b(1 To 5) As Integer Dim a As Double b(1) = 1 b(2) = 2 b(3) = 3 b(4) = 4 b(5) = 5 a = cal_var(b) MsgBox a End Sub 

它正确地返回值2。

希望这会有所帮助。

您的潜艇包含一些types不匹配,其他错误和不必要的代码。

如果我关注你,你的意思是通过部分包含数组元素来获得一系列的差异。 为了这个任务,请检查下面的代码。

 ' See http://www.cpearson.com/excel/passingandreturningarrays.htm Function cal_var(dta() As Integer) As Double() Dim N, i, j As Integer Dim tre() As Double N = UBound(dta) Dim vec_var() As Double ReDim vec_var(1 To N) For i = 1 To N ReDim Preserve tre(1 To i) tre(i) = dta(i) vec_var(i) = Application.WorksheetFunction.Var_P(tre) Next i cal_var = vec_var() End Function Sub test() Dim b(1 To 5) As Integer Dim a() As Double b(1) = 1 b(2) = 2 b(3) = 3 b(4) = 4 b(5) = 5 a = cal_var(b) ' See http://www.mrexcel.com/forum/excel-questions/562103-display-array-msgbox.html Dim myArray() As Variant Dim txt As String Dim i As Long For i = LBound(a) To UBound(a) txt = txt & a(i) & vbCrLf Next i MsgBox txt End Sub 

看到

通过函数返回数组

在MsgBox中显示数组