【问题标题】:VBA Office: Compile error: Next without ForVBA Office:编译错误:Next without For
【发布时间】:2019-02-25 21:17:21
【问题描述】:

我不确定我的代码是什么导致了编译错误。我已经缩进并做了我能想到的所有其他事情来让它工作,但它没有发生。 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

【问题讨论】:

  • Do 缺少循环直到。看起来您在 Do 关键字后面紧跟了直到子句;它需要在行块的末尾才能重复。
  • 更准确地说,Do Until 块末尾的Next 应该是LoopNextFor 语句一起使用。

标签: vba office365 next


【解决方案1】:

所以,继续我的评论。

Do Until (Cells(i, 2).Value = False)
    'statements to repeat
Loop 

【讨论】:

    【解决方案2】:

    错了几件事:

    • 您的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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-30
      • 1970-01-01
      • 2015-05-14
      • 1970-01-01
      • 2017-03-22
      • 2018-10-08
      • 1970-01-01
      相关资源
      最近更新 更多