简体   繁体   中英

Conditional formatting in Excel using VBA

I am extremely new to VBA world and need some assistance with the VBA side of conditional formatting.

  1. I need conditional formatting to be applied TO COLUMN (B4-B71),(D4-D71),(F4-F71),(H4-H71),(J4-J71),(L4-L71),(N4-N71),(P4-P71),(R4-R71) WHICH SATISFY a CONDITION AS BELOW. Examplw, valid for H4 cell =$H$4=XLOOKUP($H$4;$U$13:$U$1146;$V$13:$V$1146)THEN CHANGE TO YELLOW COLOR.

tHERE WILL BE NAMES IN THE EVERY CELL IN THE ABOVE COLUMNS AND EVERY CELL WILL CHECK THE INFORMATION IN THE COLUMN (U13-U1146).För exampl, IF THE iNFORMATIONS in cell H4 matches with the information in u column then H4 will be highlighted. the same will be applied to all the cells for above mentioned column.

and the code will be valid for apx.31 sheets in the workbook, will contain same information and same kind of conditional formatting.

Below code creates a public sub that defines the conditional formatting rules. Function funcApplyContitionalFormatting applies the specified rules from mentioned Sub .

Public Sub condFormat(ws as Worksheet, startCol as Long, startRow as Long, fRow As Long, formattingRule as String, interiorColor as Long, fontColor as Long)

    Dim rng As Range
    Set rng = ws.Range(ws.Cells(startRow , startCol), ws.Cells(fRow, startCol))
    
    rng.FormatConditions.Delete
    rng.FormatConditions.Add Type:=xlExpression, Formula1:= _
        formatRule 
     
    rng.FormatConditions(rng.FormatConditions.Count).SetFirstPriority
              
    rng.FormatConditions(1).Font.Color = fontColor 
    rng.FormatConditions(1).Interior.Color = interiorColor 
  
End Sub

Here are the function that applies the formatting rule above (also using a table/listobject to get the final row with data in that table):

Public Function funcApplyConditionalFormatting()

    Dim ws As Worksheet
    Set ws = ThisWorkbook.Worksheets("Sheet1")
    
    Dim lo As ListObject
    Set lo = ws.ListObjects("yourTable")  
    fRow = lo.DataBodyRange.Rows.Count
    
    Application.ScreenUpdating = False
    
    'Call functions
    condFormat(ws, 4, 3, fRow, "YourFormulaHere", 65535, 65535)

    
    Application.ScreenUpdating = True
    
End Function

You'd need to change inputs to suit your specific requirements, but this works for general formatting with VBA.

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