是否可以在其中更新 For End 参数



我想在 For 中更改我的 For "End" 参数。

例如:

ForEnd = 3
for i = 1 To ForEnd
   If Something = "TRUE" Then
      ForEnd = ForEnd + 1
   End If
Next i

这不起作用,因为一旦代码通过第一行,就会定义"结束"或"上限"参数。即使我在代码中更改它,它也会考虑原始值。

有什么想法吗?

谢谢。

正如 Olff 提到的,将 for 循环替换为 while-loop:

ForEnd = 3
i = 1
while i<ForEnd
   If Something = "TRUE" Then
      ForEnd = ForEnd + 1
   End If
   i = i + 1
Wend

要非常小心,不要陷入无限循环!(Something需要与"TRUE"不同(

另一种方法(更现代的方法(是使用Do..Loop方法:

ForEnd = 3
i = 1
Do While i<ForEnd
   If Something = "TRUE" Then
      ForEnd = ForEnd + 1
   End If
   i = i + 1
Loop
我不知道

为什么你需要增加结尾,为什么你不能使用其他选项作为Do...Loop,但这可能对你有用。尝试使其适应您的需求:

Dim ForEnd As Byte 'Limit or FOR...NEXT
Dim i As Byte 'Counter of FOR...NEXT
Dim XX As Byte 'It will store the last value of i when we restart the FOR...NEXT
Dim Something As String
ForEnd = 3
XX = 1 'First value of i
For_Start:
For i = XX To ForEnd Step 1
    If Something = "TRUE" Then
        ForEnd = ForEnd + 1
        XX = i + 1
        GoTo For_Start
    End If
Next i

你用另一个变量处理循环的最后一个位置,然后用一个GoTo从那里重新启动它

在标题中使用常量或变量时,无法控制For周期的上限。但是,使用函数将执行以下操作:

for i = 1 To ForEnd(i)
      ' commands
Next i
Function ForEnd(k as Long) As Long
     If Something = "TRUE" Then
        ForEnd = 0
     Else
        ForEnd = k + 1
     End If
End Function

虽然我宁愿使用上面的Do While。如果您需要For循环,那么您可以使用Exit For来中断循环,以防:

for i = 1 To 111111
    If Something = "False" Then Exit For
Next i

您可以使用:

Option Explicit
Sub test()
    Dim i As Long
    i = 1
    Do Until i > 6
        ThisWorkbook.Worksheets("Sheet1").Cells(i, 1).Value = 20
        i = i + 1
    Loop
End Sub

最新更新