Excel VBA使用来自另一个单元格的值作为条件格式的公式

时间:2014-09-08 04:03:05

标签: excel vba excel-vba

我很抱歉这么愚蠢的问题,我自己也不是一个程序员,而且我已经从我在互联网上找到的那些东西上拼凑了一个宏,我离开了只是一行代码,我根本无法得到答案。

除了条件格式化位之外,我已经完成了我想要宏执行的所有操作。问题是我希望它将格式(绿色单元格)应用于大于当前所在单元格上方4行的单元格值的单元格,然后将不同格式(红色单元格)应用于具有较低格式的单元格值不是同一个单元格的值(上面4行),但这次我需要将值设为负值。

问题在于我不知道如何告诉宏查找我所站立的4行以上的单元格的值,并且,一旦完成,如何告诉宏更改单元格的符号(乘以-1)

这是我遇到麻烦的代码。

    Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlGreater, _
        Formula1:
    Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
    With Selection.FormatConditions(1).Font
        .Color = -16752384
        .TintAndShade = 0
    End With
    With Selection.FormatConditions(1).Interior
        .PatternColorIndex = xlAutomatic
        .Color = 13561798
        .TintAndShade = 0
    End With
    Selection.FormatConditions(1).StopIfTrue = False
    Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlLess, _
        Formula1:
    Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
    With Selection.FormatConditions(1).Font
        .Color = -16383844
        .TintAndShade = 0
    End With
    With Selection.FormatConditions(1).Interior
        .PatternColorIndex = xlAutomatic
        .Color = 13551615
        .TintAndShade = 0
    End With
    Selection.FormatConditions(1).StopIfTrue = False

正如你所看到的那样,我已经离开了Formula1:空的,我想告诉宏寻找四个单元格之上的值我在那里在

下一个Formula1:空的需要查找上面四个单元格的值,然后多次-1或者将值更改为负值。

我希望你能在这里帮助我。 (对不起那些邋english的英语和糟糕的拼写,而不是我原生的语言)

1 个答案:

答案 0 :(得分:0)

您实际上并不需要使用格式调节。 无论如何,下面是演示如何做到这一点的工作代码。请注意,乘以(-1)是危险的。想象一下,如果你不止一次运行宏会发生什么?

Option Explicit
Sub conditional_formatting1()
Dim rng As Range
Set rng = Application.Selection
Dim c As Range

For Each c In rng.Cells
    c.FormatConditions.Delete

    If c.Value < c.Offset(-4).Value Then

        'setting color to red
        c.Interior.Color = RGB(255, 0, 0)
        'multipyling -1
        c.Value = c.Value * (-1)

    Else

        With c


            .FormatConditions.Add xlExpression, Formula1:="=" & c.Address & ">" & c.Offset(-4)
            'implementatio of what you wanted to do below is commented.
            'uncomment it if you want to use it or continue using what I have done below

'            With .FormatConditions(1).Font
'                .Color = -16383844
'                .TintAndShade = 0
'            End With
'            With .FormatConditions(1).Interior
'                .PatternColorIndex = xlAutomatic
'                .Color = 13551615
'                .TintAndShade = 0
'            End With

            'changing cell color to green
            c.Interior.Color = RGB(0, 255, 0)
        End With

    End If
Next c


End Sub
相关问题