For-Loop在第一轮退出

说明:代码的目标是更新一个单元格,基于来自同一行上三个单元格连接的最后更新。 “X”用于捕获这三个单元格的更新。 我知道,在“范围”我每次select一个单元格。

我写了下面的代码(也评论了以前的尝试),但我意识到我只得到一行更新。 无论它们中有多less被正确填充。

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 

我有一个“价值”分配的任何退出function的原因是什么?

任何原因为什么?

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