簡體   English   中英

使用VBA將不同的條件格式應用於一系列單元格

[英]Using VBA to apply different conditional formatting to a range of cells

試圖感受如何進行。 我讓最終用戶向我提供了需要在excel中的多個列中進行驗證的信息。

由於輸入的數據很可能會從源電子表格中復制和粘貼,因此使用數據驗證將很困難。

為了保持驗證的准確性,我將數據布局鏡像到名為“規則”的工作表中,並輸入了我想用於各列的公式。

例如:在單元格A2中,我具有以下內容:= NOT(AND(LEN(A2)<51,= IF(A2 <>“”,SUMPRODUCT(LEN(A2)-LEN(SUBSTITUTE(LOWER(A2),Validations! $ A $ 2:$ A $ 41,“”)))= LEN(A2))))這將是對A列中除A1以外的所有單元格都將繼續進行的數據驗證。

單元格B2中將具有相應的公式,依此類推,直到第BY列。

我下面的代碼是對單列的發生情況的粗略估計,而無需從單元格值中獲取條件公式:

Sheets("TestInput").Select
    With Range("A2:A60000")
        .FormatConditions.Delete
        .FormatConditions.Add Type:=xlExpression, Formula1:= _
        "=IF(A2<>"""",NOT(AND(LEN(A2)<51,SUMPRODUCT(LEN(A2)-LEN(SUBSTITUTE(LOWER(A2),Validations!$A$2:$A$41,"""")))=LEN(A2))))"
        With .FormatConditions(1).Font
            .Bold = True
            .Italic = False
            .TintAndShade = 0
        End With
        With .FormatConditions(1).Interior
            .PatternColorIndex = xlAutomatic
            .Color = 255
            .TintAndShade = 0
        End With
        .FormatConditions(1).StopIfTrue = False
    End With

我的理想終點是,在“規則”單元格“ A2”中找到A2-A60000的條件格式設置規則/公式,而在“規則”單元格中找到B2-B60000的格式設置規則/公式,這是我的理想選擇B2”,依此類推,直到“列BY”為止。

預先感謝您瀏覽!

提姆

解決方案非常簡單。 您已經完成了90%的過程。 只需在單元格A2和B2中定義您的公式,不使用=或其他任何內容即可(參見示例)。

公式范例

這是您改進的代碼:

Sub repaint()
    Dim ws As Worksheet, wsRules As Worksheet

    'Disable updates/events
    Application.ScreenUpdating = False
    Application.EnableEvents = False

    'Define here your worksheets
    Set ws = Table1
    Set wsRules = Table2

    'Clear and reset format conditions in column A
    With Range(ws.Cells(2, 1), ws.Cells(60000, 1))
        .FormatConditions.Delete
        .FormatConditions.Add Type:=xlExpression, Formula1:="=" & wsRules.Cells(2, 1).Text
        With .FormatConditions(1)
            'TODO format your stuff
        End With
    End With

    'Clear and reset format conditions in column B
    With Range(ws.Cells(2, 2), ws.Cells(60000, 2))
        .FormatConditions.Delete
        .FormatConditions.Add Type:=xlExpression, Formula1:="=" & wsRules.Cells(2, 2).Text
        With .FormatConditions(1)
            'TODO format your stuff
        End With
    End With

    'Enable updates/events
    Application.ScreenUpdating = True
    Application.EnableEvents = True
End Sub

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM