首页 > 解决方案 > 是否可以在其中更新 For End 参数?

问题描述

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

例如:

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

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

有什么想法吗?

谢谢你。

标签: excelvba

解决方案


正如 Olff 所说,将 for 循环替换为 while 循环:

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

推荐阅读