【问题标题】:How to Make a For-Each Loop Run Backwards如何使 For-Each 循环向后运行
【发布时间】:2018-11-14 01:05:36
【问题描述】:

我在 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

【问题讨论】:

  • 感谢大家的回答,感谢您的帮助!

标签: vba excel for-loop foreach


【解决方案1】:

在这种情况下,可能像这样的一些 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 继续。

【讨论】:

    【解决方案2】:

    Richard,您完全正确,“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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-22
      • 1970-01-01
      • 2021-01-21
      相关资源
      最近更新 更多