alex2002
alex2002

Reputation: 161

Conditional formatting cell error

The code I have below is checking two worksheets in order to see if the values inserted in the specific column are similar. For example, it looks to see if the values inserted in column A from sheet1 are the same as the values inserted in sheet2 column B. If yes, then the cells in sheet1 column A remain 'white' otherwise, they turn 'red'. The code works without any problems and really fast.

My problem is the following. Lets say:

I hope I explain myself somehow. Thanks for your help!

Private Sub CommandButton1_Click()

Set wb = Excel.ActiveWorkbook
Set aRec = wb.Worksheets(1)
Set bRec = wb.Worksheets(2)

Application.ScreenUpdating = False

For a = 2 To aRec.Cells(Rows.Count, "A").End(xlUp).Row
    match = Application.match(aRec.Cells(c, 1).Value, bRec.Columns(2), 0)

If IsError(match) Then
     aRec.Cells(c, 1).Interior.Color = RGB(255, 0, 0)

Else
    aRec.Cells(c, 1).Interior.Color = RGB(255, 255, 255)

End If

    Next c

End Sub

Upvotes: 0

Views: 23

Answers (1)

QHarr
QHarr

Reputation: 84465

Like?

Private Sub CommandButton1_Click()

Set wb = Excel.ActiveWorkbook
Set aRec = wb.Worksheets(1)
Set bRec = wb.Worksheets(2)

Application.ScreenUpdating = False

For a = 2 To aRec.Cells(Rows.Count, "A").End(xlUp).Row
    Match = Application.Match(aRec.Cells(a, 1).Value, bRec.Columns(2), 0)

    If IsError(Match) And Not IsEmpty(aRec.Cells(a, 1)) Then
        aRec.Cells(a, 1).Interior.Color = RGB(255, 0, 0)

    Else
        aRec.Cells(a, 1).Interior.Color = RGB(255, 255, 255)

    End If

Next a

End Sub

With correct loop variable, Option Explicit, type declarations and switching screenupdating back on

Option Explicit

Private Sub CommandButton1_Click()

Dim wb As Workbook
Dim aRec As Worksheet
Dim bRec As Worksheet
Dim a As Long
Dim Match As Variant

Set wb = ActiveWorkbook
Set aRec = wb.Worksheets(1)
Set bRec = wb.Worksheets(2)

Application.ScreenUpdating = False

For a = 2 To aRec.Cells(Rows.Count, "A").End(xlUp).Row

    Match = Application.Match(aRec.Cells(a, 1).Value, bRec.Columns(2), 0)

    If IsError(Match) And Not IsEmpty(aRec.Cells(a, 1)) Then
        aRec.Cells(a, 1).Interior.Color = RGB(255, 0, 0)
    Else
       aRec.Cells(a, 1).Interior.Color = RGB(255, 255, 255)
    End If

Next a

Application.ScreenUpdating = True

End Sub

Upvotes: 1

Related Questions