chr*_*ney 4 excel vba loops for-loop excel-vba
背景
我有一个事件的票证分配电子表格.电子表格的每一行都是名称和分配的故障单数量.
我需要更改电子表格,以便每个票证在不同的行上复制一次,如下所示:
我有一个宏来做这件事,但它表现出奇怪的行为
问题
宏不会遍历整个数据集.逐句通过代码显示,尽管刻意增加的值LastRow,For循环回路唯一指定原值但是很多次.LastRow每次迭代结束时的新值似乎被忽略.
这似乎特别奇怪,因为等效的Do While循环工作正常(请参阅下面的使用Do While循环的工作代码)
问题
为什么会出现问题部分(上面)中描述的行为,为什么它与等效结构不一致?
For循环宏
Sub InsertSurnames()
Dim LastRow As Long
Dim r As Long
Dim surname As String
Dim tickets As Integer
Dim surnameCol As Integer
Dim ticketCol As Integer
Dim targetCol As Integer
surnameCol = 1
ticketCol = 3
targetCol = 4
LastRow = ActiveSheet.UsedRange.Rows(ActiveSheet.UsedRange.Rows.Count).Row
For r = 1 To LastRow
surname = Cells(r, surnameCol).Value
tickets = Cells(r, ticketCol).Value
If (Not (Len(surname) = 0)) Then
Cells(r, targetCol).Value = surname
For x = 1 To tickets - 1
Cells(r + x, 1).EntireRow.Insert
Cells(r + x, targetCol).Value = surname
Next x
LastRow = LastRow + tickets - 1
End If
Next r
End Sub
Run Code Online (Sandbox Code Playgroud)
Do While循环宏
Sub InsertSurnames()
Dim LastRow As Long
Dim r As Long
Dim surname As String
Dim tickets As Integer
Dim surnameCol As Integer
Dim ticketCol As Integer
Dim targetCol As Integer
surnameCol = 1
ticketCol = 3
targetCol = 4
LastRow = ActiveSheet.UsedRange.Rows(ActiveSheet.UsedRange.Rows.Count).Row
r = 1
Do While r <= LastRow
surname = Cells(r, surnameCol).Value
tickets = Cells(r, ticketCol).Value
If (Not (Len(surname) = 0)) Then
Cells(r, targetCol).Value = surname
For x = 1 To tickets - 1
Cells(r + x, 1).EntireRow.Insert
Cells(r + x, targetCol).Value = surname
Next x
LastRow = LastRow + tickets - 1
End If
r = r + 1
Loop
End Sub
Run Code Online (Sandbox Code Playgroud)
编译器以不同方式交互'For'Loop构造,并使用不同的程序集调用将临时变量放入CPU缓存中,因此在每次迭代之后它不需要返回RAM来读取变量,它只需抓住它来自cpu的缓存.这是为了提高性能,这就是为什么'For'循环通常比'While'循环更快.'for'循环的限制变量仍然存在于内存中,但在每次迭代期间都不会读取它.因此,如果更改用于最初设置上限的变量,则循环仍将运行到您将其设置为的原始边界.while循环在每次迭代时检查其exit子句,而不缓存是变量.通常,当您有一定量的迭代时,应使用'For'循环,