Search code examples
excelvbafor-loopcomparison

How to check for equal values in cells with a for loop?


I want to check if the text value in a cell is the same as in the cell below with a for loop.

If the value in Cell(1) and Cell(2) does not match I want the value from Cell(3) written in Cell(4).

I get an error

"Overflow (Error 6)"

Dim i As Integer

For i = 1 To Rows.Count

    If Cells(2 + i,21) = Cells(3 + i,21) Then
        i = i + 1
    Else
        a = Cells(3 + i, 1)
        j = j + 1
        Cells(228 + j, 3) = a
    End If

Next i

End Sub

I have a production output and a timeline from 6 am to 12 am and I want to create a timetable as seen below.

Screenshot:

enter image description here


Solution

  • You could use

    Option Explicit
    
    Sub test()
    
        Dim LastRowA As Long, i As Long, j As Long, LastRowW As Long
        Dim StartTime As Date, EndTime As Date, strOutPut
    
        j = 0
    
        With ThisWorkbook.Worksheets("Sheet1")
    
            LastRowA = .Cells(.Rows.Count, "A").End(xlUp).Row
    
            For i = 3 To LastRowA
    
                If i > j - 1 Then
    
                    StartTime = .Range("A" & i).Value
                    strOutPut = .Range("U" & i).Value
    
                    For j = i + 1 To LastRowA + 1
    
                        If strOutPut <> .Range("U" & j).Value Then
    
                            EndTime = .Range("A" & j - 1).Value
                            LastRow = .Cells(.Rows.Count, "W").End(xlUp).Row
    
                            .Range("W" & LastRow + 1).Value = StartTime
                            .Range("X" & LastRow + 1).Value = EndTime
                            .Range("Y" & LastRow + 1).Value = strOutPut
    
                            Exit For
    
                        End If
    
                    Next j
    
                End If
    
            Next i
    
        End With
    
    End Sub
    

    Result

    enter image description here