澄清:代码的目标是根据同一行上三个单元格串联的最后更新来更新单元格。 “X”用于捕获这三个单元的更新。我知道在“范围”中我每次都会选择一个单元格。
我编写了以下代码(还评论了之前的尝试),但我意识到我只更新了一行。无论其中有多少被正确填写。
If Hrg.Row = Irg.Row And Irg.Row = Jrg.Row Then
For i = 2 To Hrg.Row
If (Cells(i, 11).Value = "X") Then
S(i - 1) = Cells(i, 5).Value & " " & Cells(i, 6).Value & " [" & Cells(i, 8).Value & "] " & Format(Now(), "yyyy-MM-dd hh:mm:ss") & vbLf & Cells(i, 9).Value
cellname = "I" & i
' ws.Range(cellname) = S
' Cells(i, 9) = S
' Cells(i, 9).Value = S
Else
S(3 - i) = ""
End If
Next i
cellname = "I2:I" & Hrg.Row
For Each selectedCell In ws.Range(cellname)
i = 1
If (Not (S(i) = "")) Then
selectedCell.Value = S(i)
Cells(i, 9).Value = S(i)
Cells(i, 11).ClearContents
i = i + 1
End If
Next selectedCell
有什么原因导致我在完成“值”分配后立即退出该函数吗?
有什么理由吗?
Excel 2016 VBA
最佳答案
我认为代码的第二部分存在逻辑错误。无论如何,您都会重置 i=1
:
For Each selectedCell In ws.Range(cellname)
i = 1 ' <-- you're updating the same cell over and over again
If (Not (S(i) = "")) Then
'...
i = i + 1
End If
Next selectedCell
您可能希望在循环之前初始化i=1
,并在每次迭代后递增它:
i = 1 ' <-- inititalize once, outside the loop
For Each selectedCell In ws.Range(cellname)
'....
i = i + 1 ' <-- increment i after each iteration
Next selectedCell
关于excel - For-Loop 在第一轮退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43346980/