我不确定我的代码会导致编译错误。我已经缩进并完成了我能想到的所有其他事情,以使它起作用,但那没有发生。 VBA中的错误突出显示了查找平均值时发生的第一个错误。我正在使用MBP,但我怀疑与该错误有关。
Sub Stdev()
'Declare my variables
Dim N, i, j As Integer
Dim sumofnum, sumofEsq, Xbar, Variance As Double
'Initialize variables to zero
sumofnum = 0
sumofEsq = 0
Xbar = 0
Variance = 0
'Initialize N, the number of measurements in the sample
N = 15
'Calulate the average Xbar using a For Next loop. The i increments by 1 each time through the ‘loop when it reaches the Next statement.
For i = 1 To N
Do Until (Cells(i, 2).Value = False)
If (Cells(i, 2).Value = True) Then
sumofnum = sumofnum + (Cells(i, 2).Value)
End If
Cells(i, N).Value = 15
Next
'Cells in vba is used to reference the cells in the spreadsheet by (row, column)
Xbar = sumofnum / N
'Calculate the variance. Here i increments across each column in the data.
For j = 1 To N
sumofEsq = sumofEsq + (Cells(j, 2).Value - Xbar) ^ 2
Next
'Calculate the population standard deviation
‘Variance = sumofEsq / N
'if you want the sample standard deviation
Variance = sumofEsq / (N - 1)
StdDev = Sqr(Variance)
Cells(2, 18).Value = StdDev
End Sub
答案 0 :(得分:1)
所以,进一步谈我的看法。
Do Until (Cells(i, 2).Value = False)
'statements to repeat
Loop
答案 1 :(得分:1)
一对夫妇错了:
您的for
循环需要以Next <what>
,并且您的Do
循环必须以Loop Until <condition>
或者Do Until <condition> ... code.... Loop
因此您的代码应如下所示:
For i = 1 To N
Do Until (Cells(i, 2).Value = False)
If (Cells(i, 2).Value = True) Then
sumofnum = sumofnum + (Cells(i, 2).Value)
End If
Cells(i, N).Value = 15
Loop
Next i
'Cells in vba is used to reference the cells in the spreadsheet by (row, column)
Xbar = sumofnum / N
'Calculate the variance. Here i increments across each column in the data.
For j = 1 To N
sumofEsq = sumofEsq + (Cells(j, 2).Value - Xbar) ^ 2
Next j