Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Excel VBA color cell based on value in two other cells

I am trying to fill cells in a range with color based on the values of two other cells.

I work with the table below:

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I want to color cells where Type = "B" and Helper1 = 1 or where Type = "C" and Helper 2 = 1.

Desired result:

enter image description here

I was able to achieve this using conditional formatting, however because I cannot copy the cond formatting to other workbooks (due to missing helper rows), I need to do it in VBA.

Can anyone point me into the right direction here?

Thanks a lot!

>Solution :

Just loop trough each cell and check if first column equals B or C and if row 1 or 2 of data equals to 1

Application.ScreenUpdating = False
Dim rng As Range

For Each rng In Range("A1").CurrentRegion
    If rng.Column = 1 Or rng.Row = 1 Or rng.Row = 2 Then
        'do nothing, headers and first column
    Else
        If Cells(rng.Row, 1) = "B" And Cells(1, rng.Column) = 1 Then rng.Interior.Color = vbYellow 'if first column=B and Helper1=1
        If Cells(rng.Row, 1) = "C" And Cells(2, rng.Column) = 1 Then rng.Interior.Color = vbYellow 'if first column=B and Helper2=1
    End If
Next rng
Application.ScreenUpdating = True

enter image description here

Notice Column H got no yellow color because Helper1 and Helper2 are both zeros (I did that for testing purposes)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading