【问题标题】:Excel VBA use value from another cell as formula for conditional formatingExcel VBA 使用来自另一个单元格的值作为条件格式的公式
【发布时间】:2015-02-10 06:38:35
【问题描述】:

对于这样一个愚蠢的问题,我很抱歉,我自己不是程序员,我一直在从互联网上找到的位中拼凑出一个宏,我只剩下几行代码我根本无法得到答案。

我已经完成了我想让宏做的所有事情,除了条件格式位。问题是我希望它将格式(绿色单元格)应用于大于我当前所在的单元格上方 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: 留空,这就是我想告诉宏查找我所在的单元格上方四个单元格的值

下一个公式1:空的需要查找上面四个单元格的值,然后乘以-1或将值更改为负数。

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

【问题讨论】:

标签: vba excel


【解决方案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

【讨论】:

  • 非常感谢,我能够稍微调整您的代码并让它与整个宏一起使用,再次感谢您的时间
  • 标记为答案,请或发布更多信息。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-02
  • 1970-01-01
  • 2014-12-27
  • 2020-06-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多