简体   繁体   English

VBA function 测试单元格是否在 Excel 中有条件地格式化

[英]VBA function to test if cell is conditionally formatted in Excel

I have written the function below to test if a cell has conditional formatting activated based upon the cell fill.我在下面编写了 function 来测试单元格是否根据单元格填充激活了条件格式。

Function cfTest(inputCell)

    If inputCell.DisplayFormat.Interior.Color <> 16777215 Then
        cfTest = True
    Else
       cfTest = False
    End If
End Function

It does not work however.但是它不起作用。 Saying that, this method does.话虽如此,这种方法确实有效。

Sub myCFtest()
Dim R As Integer
R = 2
Do
    If Range("I" & R).DisplayFormat.Interior.Color <> 16777215 Then
        Range("K" & R).Value = True
    Else
        Range("K" & R).Value = False
    End If

    R = R + 1

Loop Until R = 20
End Sub

Can anyone explain to me why the function will not work?谁能向我解释为什么 function 不起作用?

Cheers.干杯。

EDIT : Updated function but not working for conditional formatting编辑:更新了 function 但不适用于条件格式

Function cfTest(inputCell)
    If inputCell.Interior.ColorIndex <> -4142 Then
        cfTest = True
    Else
       cfTest = False
    End If
End Function

Here is a working demo if the desired result. 如果想要的结果,这是一个有效的演示。 Column E looks at column D and displays the value TRUE if it is conditionally formatted by cell fill color. E列将查看D列,如果它是通过单元格填充颜色有条件地格式化的,则显示值TRUE。 ie click on the name 'Bob', and conditionally formatting highlights the cell via the code below 例如,单击名称“ Bob”,然后通过下面的代码有条件地格式化突出显示单元格

=IF(AND(CELL("row")=ROW(D1),CELL("col")=COLUMN(D1)),TRUE)

在此处输入图片说明

Click on another name, and the same result occurs. 单击另一个名称,并且会出现相同的结果。

在此处输入图片说明

However, when I click off the names onto another cell, I last name selected remains highlighted, giving the impression of a button still depressed. 但是,当我将名称单击到另一个单元格上时,我选择的姓氏仍突出显示,给人的印象仍然是按下的。

在此处输入图片说明

The VBA code behind is as follows. 后面的VBA代码如下。

This sits within the Sheet1 code: 它位于Sheet1代码内:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

If Target.Column = 4 And Target.Row <= Application.WorksheetFunction.CountA(Range("D:D")) Then
    Range("D:D").Calculate
    Call cfTest

End If

End Sub

And this is the method itself: 这就是方法本身:

Sub cfTest()

Range("E:E").ClearContents

If ActiveCell.DisplayFormat.Interior.color <> 16777215 Then
    ActiveCell.Offset(0, 1) = True
End If

End Sub

The application I ended up building off this example had much more too it, but going back to the posted question, the cfTest() method allowed me to test if a cell was conditionally formatted based upon cell fill. 我最终在此示例中构建的应用程序还有很多,但是回到发布的问题,cfTest()方法允许我测试是否根据单元格填充条件对单元格进行了格式化。

I'm not sure as to the why of this but maybe it'll help. 我不确定为什么会这样,但也许会有所帮助。 VB doesn't seem to allow access to a cells color when that color is based on conditional formatting. 当VB基于条件格式设置时,VB似乎不允许访问该单元格颜色。

For example.. 例如..

'cell A1 colored yellow through conditional formatting
MsgBox Range("A1").Interior.ColorIndex
'returns the incorrect result of -4142 regardless of cell color

'cell B1 colored yellow via the fill option on the ribbon
MsgBox Range("B1").Interior.ColorIndex
'returns the correct result of 6

That being said, is there a reason you couldn't just test the cell for whatever formatting rules you have in effect. 话虽这么说,是有原因的,您不能仅仅测试单元格中是否有有效的格式化规则。 That would eliminate the need for a UDF. 这将消除对UDF的需求。

=IF(A1<50,False,True)

Here are two related functions that implement mathematical conditions. 这是实现数学条件的两个相关函数。 This is slightly less complicated than the Chip Pearson version, and also less complete, but I think this should cover most cases, and this shouldn't be too difficult to extend. 它比Chip Pearson版本要稍微复杂一些,也不太完整,但是我认为这可以涵盖大多数情况,并且扩展起来应该不会太困难。

Function isConditionallyFormatted(rng As Range) As Boolean

    Dim f As FormatCondition

    On Error Resume Next
    isConditionallyFormatted = False
    For Each f In rng.FormatConditions

        isConditionallyFormatted = checkFormula(rng.Value, f.operator, f.Formula1)
        isConditionallyFormatted = checkFormula(rng.Value, f.operator, f.Formula2)

        Next

End Function

Function checkFormula(rng As Variant, operator As Variant, condition As Variant)

    On Error GoTo errHandler:

    Dim formula As String
    condition = Right(condition, Len(condition) - 1)
    Select Case operator

            Case xlEqual: formula = rng & "=" & condition
            Case xlGreater: formula = rng & ">" & condition
            Case xlGreaterEqual: formula = rng & ">=" & condition
            Case xlLess: formula = rng & "<" & condition
            Case xlLessEqual: formula = rng & "<=" & condition
            Case xlExpression: formula = condition

            End Select

    checkFormula = Evaluate(formula)
Exit Function
errHandler:
    Debug.Print Err.Number & " : " & Err.Description
End Function

This will work for some common operators, but there are two other operators (xlBetween and xlNotBetween) and there are other types of condition that would have to be caught as well, and the logic for some of those would be a little more complicated than this. 这将对某些常见的运算符起作用,但是还有其他两个运算符(xlBetween和xlNotBetween),还必须捕获其他类型的条件,其中某些条件的逻辑要比这复杂一些。 Some of them, however (like databars), inherently convey that there is a condition, so no processing would be necessary. 但是,其中一些(例如数据栏)固有地传达了存在条件,因此不需要进行处理。

Here is a link to the full documentation: 这是完整文档的链接:

http://msdn.microsoft.com/en-us/ff835850(v=office.15) http://msdn.microsoft.com/en-us/ff835850(v=office.15)

I would perform a prior check for the color index your condition is for using this: 我将对您使用此条件的颜色索引进行事先检查:

Function cfTest_color_chk(inputCell As Range)
  cfTest_color_chk = inputCell.Interior.ColorIndex
End Function

Then your function 然后你的功能

Function cfTest(inputCell As Range)
  If inputCell.Interior.ColorIndex <> -4142 Then
      cfTest = True
  Else
     cfTest = False
  End If
End Function

Another solution to make things rock solid is to combine both function so that cfTest takes cfTest_color_chk as a parameter and cfTest_color_chk will return the value of the color to match... 使事物坚如磐石的另一种解决方案是将两个函数结合在一起,以便cfTest将cfTest_color_chk作为参数,而cfTest_color_chk将返回匹配的颜色值...

Hope this helps 希望这可以帮助

Pascal 帕斯卡

Here is UDF that allows to check if a FormatCondition is True/False for one of the cells it applies to.这是 UDF,它允许检查它适用的单元格之一的FormatCondition是否为True/False It is intended only to FormatConditions with an Operator property of xlExpression , to complete Chip Pearson version, which only tests the "fixed" Formula1 of a FormatCondition on the first cell in its AppliesTo Range .它仅用于具有xlExpressionOperator属性的FormatConditions ,以完成 Chip Pearson 版本,该版本仅在其AppliesTo Range中的第一个单元格上测试 FormatCondition 的“固定” Formula1

Function CheckFC(fc As FormatCondition, rng As Range) As Variant 'fc must must be a member of rng.FormatConditions, and rng must be in fc.AppliesTo Range
'Function CheckFC(fc As FormatCondition) As Variant 'also possible, fc.Parent(1) will be the first cell in the range from which was extracted the FormatCondition
    Set c = rng(1)
    If Intersect(c, fc.AppliesTo) Is Nothing Then Exit Function
    If Application.LanguageSettings.LanguageID(MsoAppLanguageID.msoLanguageIDUI) <> 1033 Then
        'Français; France; fr-FR; 1036
        Set temp = Cells(Selection.Parent.UsedRange.SpecialCells(xlCellTypeLastCell).Row + 1, "A")
        temp.FormulaLocal = fc.Formula1
        strFormulaMoved$ = Application.ConvertFormula( _
                                                        Application.ConvertFormula(temp.Formula, XlReferenceStyle.xlA1, XlReferenceStyle.xlR1C1, , fc.AppliesTo(1)), _
                                                        XlReferenceStyle.xlR1C1, XlReferenceStyle.xlA1, , c)
        temp.ClearContents
    Else
        'English; United States; fr-FR; 1033
        
        strFormulaMoved$ = Application.ConvertFormula( _
                                                        Application.ConvertFormula(fc.Formula1, XlReferenceStyle.xlA1, XlReferenceStyle.xlR1C1, , fc.AppliesTo(1)), _
                                                        XlReferenceStyle.xlR1C1, XlReferenceStyle.xlA1, , c)
    End If
        CheckFC = Application.Evaluate(strFormulaMoved)
End Function

Example:例子:

?CheckFC(Selection.FormatConditions(1), Selection)

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

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