excel - For-Loop 在第一轮退出

标签 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

最佳答案

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

相关文章:

excel - 多列合并为一列,以逗号分隔

excel - VBA准时取消调度

vba - 为什么 Round 产生的结果与 Application.Round 不同

matlab - 没有for循环的矩阵赋值元素

javascript - 将 for 循环的一部分放入 javascript 的函数中

vba - 复制并粘贴行和列(带有公式)并粘贴到 VBA 中的最后一行

python - 将 Excel 行、列索引转换为 python/openpyxl 中的字母数字单元格引用

c++ - 无法进行嵌套循环

java - 如何使用 OpenOffice Java API 更新 Word 文档中嵌入的 Excel 表格?

vba - 在 Outlook 尚未打开时发送邮件