简体   繁体   English

使用 VBA 在 Excel 中进行条件格式设置

[英]Conditional formatting in Excel using VBA

I am extremely new to VBA world and need some assistance with the VBA side of conditional formatting.我对 VBA 世界非常陌生,需要一些关于条件格式的 VBA 方面的帮助。

  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.我需要将条件格式应用于列 (B4-B71),(D4-D71),(F4-F71),(H4-H71),(J4-J71),(L4-L71),(N4-N71) ,(P4-P71),(R4-R71) 满足以下条件。 Examplw, valid for H4 cell =$H$4=XLOOKUP($H$4;$U$13:$U$1146;$V$13:$V$1146)THEN CHANGE TO YELLOW COLOR.示例,适用于 H4 单元格 =$H$4=XLOOKUP($H$4;$U$13:$U$1146;$V$13:$V$1146) 然后更改为黄色。

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.上面列中的每个单元格中都会有名称,每个单元格都会检查列中的信息 (U13-U1146)。例如,如果单元格 H4 中的信息与 u 列中的信息匹配,则 H4 将突出显示。 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.并且代码对工作簿中的 apx.31 工作表有效,将包含相同的信息和相同的条件格式。

Below code creates a public sub that defines the conditional formatting rules.下面的代码创建了一个定义条件格式规则的public sub Function funcApplyContitionalFormatting applies the specified rules from mentioned Sub .函数funcApplyContitionalFormatting应用来自提到的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.您需要更改输入以满足您的特定要求,但这适用于使用 VBA 进行一般格式化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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