编译错误:下一步没有For || VBA



我的代码有问题,出现了一个错误,但我没有;我不明白为什么。错误为:
"编译错误: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  

提前感谢大家,致以最良好的问候,
阿图尔。

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

示例:

For i = 1 To 10 '<---- This is the header
    Hello(i) = "Blah"  '<---- This is the body
Next i  '<---- This is the closing statement

If语句的一部分位于For i循环内部,另一部分位于外部。它必须要么全部在里面,要么全部在外面。仔细思考逻辑,看看你想做什么。

您可能有重叠的循环

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

最新更新