【问题标题】:How to apply Step -1 in a For Next to loop in reverse order?如何在 For Next 中应用 Step -1 以相反的顺序循环?
【发布时间】:2021-02-06 05:01:39
【问题描述】:

我试图让这个循环以相反的顺序检查 xCol,或者从右列到左边。它在没有 Step -1 的情况下工作(从左到右),但是当我添加 Step -1 时什么都不做。

Sub Email()
    Dim xSheet As Worksheet
    Dim xRow As Integer
    Dim xCol As Integer
    Dim lastRow As Integer
    Dim lastCol As Integer

    Set xSheet = Excel.Worksheets("Approval Process")

    lastRow = xSheet.UsedRange.Rows.Count
    lastCol = xSheet.UsedRange.Columns.Count

    For xRow = 2 To lastRow
        For xCol = 3 To lastCol Step -1
            If xSheet.Cells(xRow, xCol).Value <> "" Then
                MsgBox xRow & "," & xCol
               Exit For
            Else
                MsgBox "Blank"
            End If
        Next xCol
    Next xRow

End Sub

单元格 (C2,H5) 有“是”字样或空白。

最终目标是让循环返回每行中包含数据的最后一个单元格的行号和列号。

【问题讨论】:

  • 确保将Integer 更改为Long Excel 的行数超出Integer 的处理能力!由于使用Integer 没有任何好处,我推荐always to use Long instead

标签: excel vba loops for-loop


【解决方案1】:

当你在 FOR 循环中有负 STEP 时,你应该从更大的数字开始,并让第二个参数更小。

当您将较小的数字作为第一个输入而将较大的数字作为第二个输入时,就会出现问题。

尝试反转值到:

For xCol = lastCol To 3 Step -1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-04
    • 1970-01-01
    • 2016-05-19
    • 2020-07-25
    • 1970-01-01
    • 1970-01-01
    • 2020-05-06
    相关资源
    最近更新 更多