我遇到了VBA问题。我需要计算数组的方差。但是for循环中的数组,如果我使用Next i
,它会将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
检查我的功能
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
答案 0 :(得分:1)
根据任务描述,一个简单的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。
希望这会有所帮助。
答案 1 :(得分:0)
您的潜艇包含许多类型不匹配,其他错误和不必要的代码。
如果我关注你,你的意思是通过部分包含数组的元素来获得一系列差异。 对于该任务,请检查以下代码。
' 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
见