繁体   English   中英

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

[英]Excel VBA use value from another cell as formula for conditional formating

对于这样一个愚蠢的问题,我感到抱歉,我自己也不是程序员,我一直在通过在互联网上找到的位拼凑一个宏,而我只剩下一小段代码,我根本无法获得答案。

我已经完成了我希望宏执行的所有操作,除了条件格式化位。 问题是我希望将格式(绿色单元格)应用于大于我当前所在单元格上方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或将值更改为负值所需的任何时间。

我希望你能在这里帮助我。 (对不起,英语马虎,拼写不佳,不是我的母语)

您实际上不需要使用格式条件。 无论如何,下面是工作代码来演示如何完成此工作。 请注意,乘以(-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

暂无
暂无

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

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