Home » excel » excel – How to return cell value with For Next loop using 2 sheets and multiple conditions – VBA

excel – How to return cell value with For Next loop using 2 sheets and multiple conditions – VBA

Posted by: admin May 14, 2020 Leave a comment

Questions:

I’m attempting to match values between two sheets and if found and the conditions are met, perform the action of changing the cell colour.

PROBLEM:

I’m getting an error with my For...Next loop, even though I thought I have a NEXT for each FOR statement. Not sure what I’ve done wrong.

Also, I’m not sure my counters are setup correctly to accurately scan through each sheet/column needed. Any help would be appreciated.

Sub ReadData()

Dim wb As Workbook
Dim ws As Worksheet
Dim lastrow As Long
Dim i As Long

Set wb = ActiveWorkbook
Set ws = wb.Sheets("Ref1")
Set ws2 = wb.Sheets("TRA")
lastrow = Sheets("Ref1").Cells(Rows.Count, "A").End(xlUp).Row
lastrow2 = Sheets("TRA").Cells(Rows.Count, "A").End(xlUp).Row

Sheets("Ref1").Activate


i = 2
k = 2


For i = 2 To lastrow
    For k = 2 To lastrow2
        If Cells(i, 4).Value = "Active" Then
            If ws.Cells(i, 18).Value = ws2.Cells(i, 1).Value And (ws2.Cells(i, 23).Value <> "Cancelled" Or ws2.Cells(i, 23).Value <> "Completed") Then
    Cells(i, 20).Interior.ColorIndex = 9

End If
    Next

Next

End Sub
How to&Answers:

Quick Repair

  • To better understand the code, it is often preferable to use letters,
    instead of numbers, for columns.

The Code

Sub ReadData()

    Dim wb As Workbook
    Dim ws As Worksheet
    Dim ws2 As Worksheet
    Dim lastrow As Long
    Dim lastrow2 As Long
    Dim i As Long
    Dim k As Long

    ' Use ThisWorkbook instead of ActiveWorkbook, if the code is
    ' in the same workbook where these sheets are.
    With ActiveWorkbook
        Set ws = .Worksheets("Ref1")
        Set ws2 = .Worksheets("TRA")
    End With

    lastrow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
    lastrow2 = ws2.Cells(ws2.Rows.Count, "A").End(xlUp).Row

    For i = 2 To lastrow
        If ws.Cells(i, "D").Value = "Active" Then
            For k = 2 To lastrow2
                If ws.Cells(i, "R").Value = ws2.Cells(k, "A").Value _
                        And ws2.Cells(k, "W").Value <> "Cancelled" _
                        And ws2.Cells(k, "W").Value <> "Completed" Then
                    ws.Cells(i, "T").Interior.ColorIndex = 9 ' Brown
                    Exit For
                End If
            Next
        End If
    Next

End Sub