如何在循环内执行if语句?

时间:2018-12-04 23:28:28

标签: excel vba excel-vba loops

我在循环内使用if语句遇到麻烦。每次尝试运行它时,都会出现以下错误:

  

下一个没有for

Sub CheckDates4()

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

    count = 0
    i = 2
    j = 24

    For i = 2 To 318
        For j = 46 To 1 Step (-2)
            If Sheet1.Cells(i, j) >= Sheet2.Cells(1, 1) And Sheet1.Cells(i, j - 1) = "Reçu" Then
                count = count + 1
            Next i
        Next j

    End If

    Sheet2.Cells(1, 7) = count

End Sub

有什么办法解决这个问题吗?

2 个答案:

答案 0 :(得分:1)

您的END IF放在错误的位置,并且您也交换了NEXTs

For i = 2 To 318
    For j = 46 To 1 Step (-2)
        If Sheet1.Cells(i, j) >= Sheet2.Cells(1, 1) And Sheet1.Cells(i, j - 1) = "Reçu" Then
            count = count + 1
        End If
    Next
Next

答案 1 :(得分:1)

您应该首先使用If关闭End If条件。然后,使用For关闭内部Next j循环。最后,使用For关闭外部Next i循环。因此,您的代码应如下所示:

Sub CheckDates4()
    Dim count As Integer
    Dim i As Integer
    Dim j As Integer

    count = 0
    i = 2
    j = 24

    For i = 2 To 318
        For j = 46 To 1 Step (-2)
            If Sheet1.Cells(i, j) >= Sheet2.Cells(1, 1) And Sheet1.Cells(i, j - 1) = "Reçu" Then
                count = count + 1
            End If
        Next j
    Next i

    Sheet2.Cells(1, 7) = count
End Sub