编译错误:Next 没有 For || VBA

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18232928/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 16:25:00  来源:igfitidea点击:

Compile error: Next without For || VBA

excelvbaexcel-vba

提问by Artur Rutkowski

I have a problem with my code, an error appears, and I don;t understand why. The error is:
"Compile error: Next without For"
I do not understand why it is like that. I am new to coding so any help and comments are more than welcome.
This is the code, the Next which is pointed as the one without For is provided a comment.

我的代码有问题,出现错误,我不明白为什么。错误是:
“编译错误:Next without For”
我不明白为什么会这样。我是编码新手,因此非常欢迎任何帮助和评论。
这是代码,指向没有 For 的 Next 提供了注释。

Sub CGT_Cost()
startrow = Worksheets("GUTS").Cells(10, 1) 'Here I put 1
endrow = Worksheets("GUTS").Cells(11, 1)   'Here I put 1000

For x = endrow To startrow Step -1

If Cells(x, "Q").Value = "Sale" Then

    If Cells(x, "D").Value = "1" Then

    For i = 1 To 1000

        If Cells(x - i, "R").Value <> "1" Then

    Next i
        Else
        Range("G" & x).FormulaR1C1 = "=R[-" & i & "]C/R[-" & i & "]C[-1]*RC[-1]"

        End If
    End If
    End If
Next x  

End Sub  

Thank you all in advance, with best regards,
Artur.

提前谢谢大家,向大家
致以最诚挚的问候,阿图尔。

回答by jlaverde

Every Forstatement with a body must have a matching Next, and every If-Thenstatement with a body must have a matching End If.

每个带有正文的For语句都必须有一个匹配的Next,每个带有正文的If-Then语句都必须有一个匹配的End If

Example:

例子:

For i = 1 To 10 '<---- This is the header

    Hello(i) = "Blah"  '<---- This is the body

Next i  '<---- This is the closing statement

You have part of the body of your Ifstatement inside your For iloop, and part of it outside. It has to be either ALL inside or ALL outside. Think through the logic and see what it is you want to do.

您在For i循环中有If语句的一部分,而在外部有一部分。它必须是 ALL 内部或 ALL 外部。仔细思考逻辑,看看你想要做什么。

回答by JosieP

you have overlapping loops-perhaps

你有重叠的循环——也许

Sub CGT_Cost()
   startrow = Worksheets("GUTS").Cells(10, 1)   'Here I put 1
   endrow = Worksheets("GUTS").Cells(11, 1)   'Here I put 1000

   For x = endrow To startrow Step -1

      If Cells(x, "Q").Value = "Sale" Then

         If Cells(x, "D").Value = "1" Then

            For i = 1 To 1000

               If Cells(x - i, "R").Value <> "1" Then
                  '
               Else
                  Range("G" & x).FormulaR1C1 = "=R[-" & i & "]C/R[-" & i & "]C[-1]*RC[-1]"
               End If

            Next i

         End If

      End If

   Next x

End Sub