Home > other >  Highlight cells in a sheet based on corresponding cell values in another sheet with a macro
Highlight cells in a sheet based on corresponding cell values in another sheet with a macro

Time:06-30

I would like to create a macro that would highlight certain cells of a sheet based on another sheet values.

I have two Sheets in my excel file:

"Check" and "Formula"

I would like a macro which highlights the cells in sheet 'Check' with red color if their corresponding cells in Sheet 'Formula' are marked as "FAIL".

Note: The number of columns are not static (their is no fixed structure for no. of columns it can be 4 ,5,6 etc)

I have provided screenshots for better understanding:

Cells in Check sheets to be highlighted as Red

IF FAIL appears in Formula sheet its corresponding value in other sheet should be highlighted

CodePudding user response:

As mentioned by enter image description here

In case you say "But I don't want that True, False in the second column", you don't need to: when I create conditional formatting, based on a formula, I always check my formula in a temporary helper column and delete it afterwards :-)

CodePudding user response:

If you do not prefer Conditional Formatting, please use the next VBA code. It will place the range to be processed (from ) in an array, iterate between all array elements and create a Union Range to be colored at the end:

Sub HighlightCells()
 Dim shCh As Worksheet, shF As Worksheet, lastR As Long, lastCol As Long
 Dim rngF As Range, arrH, i As Long, j As Long, rngFAIL As Range
 
 Set shCh = Sheets("Check") 
 Set shF = Sheets("Formula")
 lastR = shCh.Range("A" & shCh.rows.count).End(xlUp).row
 lastCol = shCh.cells(1, shCh.Columns.count).End(xlToLeft).column
 
 Set rngF = shCh.Range("A2", shCh.cells(lastR, lastCol))
  rngF.Interior.Color = xlNone 'clear the previous coloring
 arrH = shF.Range("A2", shF.cells(lastR, lastCol)).Value2
 
 For i = 1 To UBound(arrH)
    For j = 1 To UBound(arrH, 2)
        If arrH(i, j) = "FAIL" Then
            Set rngFAIL = addToFAIL(rngF.cells(i, j), rngFAIL)
        End If
    Next j
 Next i
 If Not rngFAIL Is Nothing Then rngFAIL.Interior.Color = vbRed
End Sub

Function addToFAIL(rng As Range, rngFAIL As Range) As Range
  If rngFAIL Is Nothing Then
        Set addToFAIL = rng
  Else
        Set addToFAIL = Union(rngFAIL, rng)
  End If
End Function

But this is not dinamic, as it is...

In order to be dinamic you can place it in an event of the "Formula" sheet, depending on how the values (FAIL) are changed... Probable, Calculate if the changes take places in formulas, as the sheet name let us suppose.

If the Union range to be returned is huge, the code speed may be significantly decreasing, but even in such a case the situation can be handled creating (number) limitations of the range cells and color the necessary cells in steps.

  • Related