Programmatically add conditional formatting

rex759

Well-known Member
Joined
Nov 8, 2004
Messages
610
Office Version
  1. 365
Platform
  1. Windows
Hello,

My code below seems to only work if the active cell is somewhere on row 2 before I run the macro. (I have a header row)
Otherwise, the cell ranges are changed. For example, if the cursor is on B4, after I run the macro, the formula;

COUNTIF($S$2:$S$500,$A2)>0 becomes COUNTIF($S$2:$S$500,$A1048576)>0

How can I avoid activating a cell on row 2 before running the macro?

Any help is appreciated

Code:
Sub AddCondFmt()
'Add formula for validation

With Worksheets("sheet1")
    .Range("$a$2:$a$500").FormatConditions.Add Type:=xlExpression, Formula1:="=COUNTIF($S$2:$S$500,$A2)>0"
    .Range("$a$2:$a$500").FormatConditions(.Range("$a$2:$a$500").FormatConditions.Count).SetFirstPriority
End With
 
   With Range("$A$2:$A$500").FormatConditions(1).Interior
        .PatternColorIndex = xlAutomatic
        .Color = 255
        .TintAndShade = 0
    End With
    
   Worksheets("Sheet1").Range("$A$2:$A$500").FormatConditions(1).StopIfTrue = False

End sub
 

Excel Facts

Can you AutoAverage in Excel?
There is a drop-down next to the AutoSum symbol. Open the drop-down to choose AVERAGE, COUNT, MAX, or MIN
Try using R1C1 style referencing in your formula. Or select the top left cell before running your code. Unfortunately, in VBA a CF formula is relative to the active cell.
 
Upvote 0

Forum statistics

Threads
1,224,559
Messages
6,179,517
Members
452,921
Latest member
BBQKING

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top