For-Loop在第一轮退出

时间:2017-04-11 13:12:29

标签: excel vba for-loop

澄清:代码的目标是根据来自同一行上三个单元的串联的最后更新来更新单元。 “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

1 个答案:

答案 0 :(得分:2)

我认为代码的第二部分存在逻辑错误。您无论如何重置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