尝试在VBA中修复Do While循环

时间:2016-11-24 18:21:34

标签: excel vba

提前感谢您抽出宝贵时间提供帮助。我在VBA中构建了一个Do While循环,由于某种原因在j = 1时中断。我在单元格C3:C7中有这些值:13,14,14,13,14。

这是简短的脚本:

Dim i, j, n As Integer
Dim List(0) As Integer

i = o
j = 0
n = 0

Do While Cells(i + 3, 3) <> ""     

    If Cells(i + 3, 3) > 13 Then
        List(j) = i + 3
        j = j + 1
        Cells(i + 3, 4) = "Noted"
        i = i + 1
    ElseIf Cells(i + 3, 3) = 13 Then
        Cells(i + 3, 4) = "Skipped"
        i = i + 1
    Else
        i = i + 1
    End If
Loop

For n = j To n = 0
    Rows(List(n)).Delete
Next

再次感谢!

1 个答案:

答案 0 :(得分:2)

你的意图是合理的,但是有很多错误。有关详细信息,请参阅下面的注释代码

Sub Demo()
    ' ~~ must explicitly type each variable.  Use Long
    Dim i As Long, j As Long, n As Long
    Dim List() As Long '<~~ dynamic array

    i = 3 '<~~ eliminate the klunky +3
    j = 0
    n = 0
    ReDim List(0 To 0) '<~~ initialise dynamic array
    Do While Cells(i, 3) <> vbNullString
        If Cells(i, 3) > 13 Then
            ReDim Preserve List(0 To j) '<~~ resize array
            List(j) = i
            j = j + 1
            Cells(i, 4) = "Noted"
        ElseIf Cells(i, 3) = 13 Then
            Cells(i, 4) = "Skipped"
        End If
        i = i + 1 '<~~ simplify, its called in each if case anyway
    Loop

    ' j will end up 1 greater than size of array
    If j > 0 Then '<~~ only execute if we found some rows to delete
        For n = j - 1 To 0 Step -1 '<~~ For loop syntax
            Rows(List(n)).Delete
        Next
    End If
End Sub