gpt4 book ai didi

vba - 对于开始到结束循环,结束变量更改中间循环

转载 作者:行者123 更新时间:2023-12-04 00:08:10 24 4
gpt4 key购买 nike

从测试数据开始:

Start

并运行代码:

Sub TestLoop()

Dim LastRow As Long, CurRow As Long
LastRow = Range("A" & Rows.Count).End(xlUp).Row

For CurRow = 1 To LastRow
Range("B" & CurRow).Value = "Done"
LastRow = 2
Next CurRow

End Sub

我希望循环在第 2 行结束,因为我更改了变量 LastRow。然而结果是:

Done

MSDN Reference FOR VB.NET has this to say :

When a For...Next loop starts, Visual Basic evaluates start, end, and step. Visual Basic evaluates these values only at this time and then assigns start to counter. Before the statement block runs, Visual Basic compares counter to end. If counter is already larger than the end value (or smaller if step is negative), the For loop ends and control passes to the statement that follows the Next statement. Otherwise, the statement block runs.

Each time Visual Basic encounters the Next statement, it increments counter by step and returns to the For statement. Again it compares counter to end, and again it either runs the block or exits the loop, depending on the result. This process continues until counter passes end or an Exit For statement is encountered. [Emphasis mine]

鉴于它在每次迭代时都会根据 end 检查 counter,难道不应该更改变量来更改 end

最佳答案

鉴于 Correct MSDN Reference提及:

The expressions <start-value>, <end-value>, and <step-increment> are evaluated once, in order, and prior to any of the following computations.

似乎 Visual Basic 可以记住 end 的值在循环期间,即使变量包含 end数量变化。

关于vba - 对于开始到结束循环,结束变量更改中间循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27824936/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com