比较单元格并显示图标

时间:2016-11-03 16:06:32

标签: excel

我有一个excel宏,它将每个单元格与之前的单元格进行比较,并显示更大,更小或相等的图标:

Sub Up()
Dim c As Range

For Each c In Worksheets("Général").Range("D2:T20")
MFC c
Next c
End Sub

Private Sub MFC(ByVal Rng As Range)

With Rng
.FormatConditions.Delete
.FormatConditions.AddIconSetCondition
With .FormatConditions(1)
    .SetFirstPriority
    .IconSet = ThisWorkbook.IconSets(xl3Arrows)
    With .IconCriteria(2)
        .Type = xlConditionValueFormula
        .Value = "=" & Rng.Offset(, -1).Address
        .Operator = xlGreaterEqual
    End With
    With .IconCriteria(3)
        .Type = xlConditionValueFormula
        .Value = "=" & Rng.Offset(, -1).Address
        .Operator = xlGreater
    End With
End With
End With
End Sub

实际显示:

enter image description here

我只需要反转更大和更少的图标(跟踪位置:位置1优于位置2)

通缉显示:

enter image description here

1 个答案:

答案 0 :(得分:1)

考虑将 xlGreaterEqual 切换为 xlLessEqual 并将 xlGreater 切换为 xlLess 的想法,我注意到此MSDN {{3那说:

  

对于图标集条件格式规则,此属性只能设置为以下两个常量之一: xlGreater xlGreaterEqual

这是由UI重新强制执行的,其中这些是对使用图标集规则的条件格式选择的选项的限制:

article

因此,这里的解决方案可能只是反转数据上的符号,然后使用数字格式“隐藏”并使用您已发布的代码。

所以在这个例子中:

enter image description here

  • 第一个范围是根据您的示例
  • 第二个范围是每个值为*-1
  • 的示例
  • 第三个范围是第二个范围,其自定义数字格式为0;0;0,以使负数显示为正数。

代码与您的代码完全相同(我的更改是在我的工作表上的范围);这是符号切换和数字格式,可以获得您想要的输出:

Option Explicit

Sub Up()

    Dim rngSource As Range
    Dim rngCell As Range

    Set rngSource = ThisWorkbook.Worksheets("Sheet1").Range("B2:E3")

    For Each rngCell In rngSource
        MFC rngCell
    Next rngCell

    Set rngSource = ThisWorkbook.Worksheets("Sheet1").Range("B6:E7")

    For Each rngCell In rngSource
        MFC rngCell
    Next rngCell

    Set rngSource = ThisWorkbook.Worksheets("Sheet1").Range("B10:E11")

    For Each rngCell In rngSource
        MFC rngCell
    Next rngCell

End Sub

Private Sub MFC(ByVal rng As Range)

    Dim lngThisNumber As Long
    Dim lngPreviousNumber As Long

    lngThisNumber = rng.Value
    lngPreviousNumber = rng.Offset(0, -1).Value

    With rng
        .FormatConditions.Delete
        .FormatConditions.AddIconSetCondition
        With .FormatConditions(1)
            .SetFirstPriority
            .IconSet = ThisWorkbook.IconSets(xl3Arrows)
            With .IconCriteria(2)
                .Type = xlConditionValueFormula
                .Value = "=" & rng.Offset(, -1).Address
                .Operator = xlGreaterEqual
            End With
            With .IconCriteria(3)
                .Type = xlConditionValueFormula
                .Value = "=" & rng.Offset(, -1).Address
                .Operator = xlGreater
            End With
        End With
    End With

End Sub

请注意,我为.Value作业尝试了此操作:

.Value = "=" & rng.Offset(, -1).Address & "*-1"

因此,在应用格式化时,*-1将在运行时完成 - 但是,这根本没有获得所需的输出。