简体   繁体   中英

How to apply the conditional formatting to multiple columns using excel macro

I created a conditional formatting to change the color based on value compare for one cell, but I don't know how to apply this formatting for the whole column and even other columns? (do I have to use for loop to set the formatting for all the cells?)

'add conditionalFormating for one cell.
 Set rngCell = Cells(6, 7)
 Set objCF = rngCell.FormatConditions.Add _
            (Type:=xlExpression, _
            Formula1:="=" & rngCell.Address & " > " & rngCell.offset(, -3).Address)
'set formats for new CF

With objCF
    .Font.ColorIndex = 26
    .Interior.ColorIndex = 19
End With

Thanks in advance

Unfortunately, Excel 2007/2010 don't have as extensive a macro record function as earlier versions

If you are referencing other cells when applying conditional formatting, a good method is to apply it to one cell (which you know how to do), and then copy the formatting to the rest of the column; if you are filling down a column, this should not cause you to lose other cell formats you may wish to keep

So I would start your code with

rngCell.FormatConditions.Delete

Then once the format is added, you can simply use:

rngCell.Copy
rngOut.PasteSpecial xlPasteFormats

, where rngOut is defined as starting with rngCell and filling down to the last row in the table

To apply to other columns, you would probably need a different formula as there are different offsets. To minimise the required code, you could always manually add the full set of formats/conditional formats you want to a hidden row just above the table's headers. Then you can copy all of these to your table using code of the form...

Range("A1:J1").Copy
Range("A3:J100").PasteSpecial xlPasteFormats

...if we assume your header gets pushed down to row 2 when you add the formatted row in row 1

Although I have referred to cell addresses in the above example, I would always recommend referring to range names and using cells notation eg Range("A1") is Cells(1, 1). The use of range names to define columns in tables is covered in more detail in this expert Excel video . The benefits are immense...if your header row is defined with a range name, you can insert a new row above your table without having to re-write any code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM