VBA Office:编译错误:Next without For

Posted

技术标签:

【中文标题】VBA Office:编译错误:Next without For【英文标题】:VBA Office: Compile error: 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 语句一起使用。 【参考方案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

【讨论】:

以上是关于VBA Office:编译错误:Next without For的主要内容,如果未能解决你的问题,请参考以下文章

Excel VBA 错误:在没有 For 的情况下下一个编译错误

更新到 Office 2016 后的 VBA 脚本错误 (CreateObject("System.Collections.ArrayList"))

我想在 Excel 中使用 VBA 从 Office 365 Outlook 邮件中读取 SenderAddress?

CAD VBA调用VB编译的DLL问题

excel vba中的对象变量和With块未设置错误

编译错误:此项目中的代码必须更新