如何使For-Each循环向后运行

问题描述 投票:3回答:2

我在VBA中编写了一个小脚本,它根据列表检查给定范围内的单元格的值。如果单元格值与列表中的值匹配则保留,否则将删除。我想知道如何让它向后运行,因为向前运行会产生问题。我已经对此进行了一些研究,并且我尝试将“Step -1”附加到开始for循环的行的末尾,但是在这种情况下这不起作用。

Set Rng = Range("A9:V9")
For Each cell In Rng
    If Not myList.Exists(cell.Value) Then
        cell.EntireColumn.Delete
    End If
Next
excel vba excel-vba for-loop foreach
2个回答
6
投票

在这种情况下,可能像这样的一些for循环就足够了:

Option Explicit

Sub TestMe()

    Dim rng As Range
    Dim cnt As Long

    Set rng = Range("A9:V9")

    For cnt = rng.Cells.Count To 1 Step -1
        Cells(rng.Row, cnt) = 23
        Stop
    Next

End Sub

我已经放了Stop所以你可以看到哪个细胞被引用。一旦你击中了Stop,继续进行F5。


0
投票

理查德,你完全正确,在这种情况下,“Step -1”方法将是正确的解决方案。您只需更改周围的变量引用即可使用循环。

例如:

Set Rng = Range("A9:V9")
For i = rng.rows.count to 1 step -1
    for j = rng.columns.count to 1 step -1
        if not myList.Exists(rng.cells(i, j).value) then
           rng.cells(i, j).entirecolumn.delete ' This probably won't work, but you get the idea.
        end if
    next j
next i
© www.soinside.com 2019 - 2024. All rights reserved.