首页 > 解决方案 > 为什么我的 vba 循环每次都跳到我的外部下一个?

问题描述

所以我有一个双循环,由于某种原因总是跳到我的外循环。循环来自:

For j = lastColumn To 6 Step (-1)

至:

Next i

每一次。但是,在我的数据集中,应该在我的 if 语句中捕获各种混合数据并计算数据。

有任何想法吗?也许我错误地格式化了宏。

Sub CheckDates()


Dim count As Integer
Dim i As Integer
Dim j As Integer


Sheets(1).Select

lastrow = ActiveSheet.Cells(Rows.count, "B").End(xlUp).Row

'have to keep data in a table for this to actually work as it ctrls+left to the table, which will end where the very last text of any row is
lastColumn = ActiveSheet.Cells(1, Columns.count).End(xlToLeft).Column


count = 0
i = 3
j = lastColumn

For i = 3 To lastrow
    For j = lastColumn To 6 Step (-1)
        If Sheet1.Cells(i, j) < Sheet2.Cells(1, 1) And Sheet1.Cells(i, j - 1) = "Reçu" Then
        count = count + 1
    GoTo NextIteration
        End If
    Next j
    NextIteration:
Next i

Sheet2.Cells(1, 7) = count

Sheets(2).Select


'Runs the DeleteSAC Macro
Call DeleteSAC

End Sub

标签: excelvbaloops

解决方案


简化

对行使用Long ,对列使用Integer

当你写的时候With Sheet1,你应该写的任何地方Sheet1,例如Sheet1.Range(whatever)...你可以写.Range(whatever),直到你用End With 结束

Exit For仅退出它所在的For 循环。因此,它与您对Goto行所做的完全相同,但您正在使用更多行。

当您使用 Sheet1 或 Sheet2 等时,您实际上是在使用代码名称,因此您可以更改选项卡中的名称,代码仍将运行。

当您逐行删除时,通常使用向后计数,因此无需这样做,因为您只是在计数。

Option Explicit

Sub CheckDates()

    Dim dataCount As Long
    Dim i As Long
    Dim j As Integer
    Dim lastrow As Long

    With Sheet1
        
        lastrow = .Cells(.Rows.count, "B").End(xlUp).Row

        'have to keep data in a table for this to actually work as it ctrls+left
        'to the table, which will end where the very last text of any row is
        lastColumn = .Cells(1, .Columns.count).End(xlToLeft).Column

        For i = 3 To lastrow
            For j = 6 To lastColumn
                If .Cells(i, j) < Sheet2.Cells(1, 1) And .Cells(i, j - 1) = "Reçu" Then
                    dataCount = dataCount + 1
                    Exit For
                End If
            Next
        Next
    
    End With
    
    With Sheet2
        .Cells(1, 7) = dataCount
        .Select
    End With
    
    'Runs the DeleteSAC Macro
    DeleteSAC

End Sub

推荐阅读