使用多个变量在循环内循环

时间:2018-10-17 18:13:45

标签: excel vba

我无法使程序在Excel中运行。

我需要遍历excel电子表格中的所有行,并遍历每一行的多个可能单元格。

Sub DoubleLoop() 
    Dim i As Long
    Dim Carr As Integer

    For i = 2 To 49235
        For j = 2 To 27
            If Range("P" & i).Value = ("Y" & j) And Range("S" & i).Value = ("Z" & j) And Range("P" & i).Value = ("AA" & j) Then
                Range("P" & i).Value = "Keep"
            ElseIf j < 27 Then
                j = j + 1
            ElseIf j = 27 Then
                Range("X" & i).Value = "Remove"
            End If
    Next i
End Sub

1 个答案:

答案 0 :(得分:2)

如评论中所述。使用Next j并在符合条件时退出内部循环。

Sub DoubleLoop()
    Dim i As Long, j As Long
    Dim Carr As Integer

    For i = 2 To 49235
        Range("P" & i).Value = "Remove"
        For j = 2 To 27
            If Range("P" & i).Value = ("Y" & j) And Range("S" & i).Value = ("Z" & j) And Range("P" & i).Value = ("AA" & j) Then
                Range("P" & i).Value = "Keep"
                Exit For
            End If
        Next j
    Next i
End Sub