使用Excel VBA代码进行条件格式化 [英] Conditional Formatting using Excel VBA code

查看:613
本文介绍了使用Excel VBA代码进行条件格式化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为DistinationRange的Range对象,其中包含引用范围B3:H63



我想使用Excel VBA代码动态应用以下两个条件格式。 (因为范围不一致)



  1. 如果单元格列D为空白,则无格式化应该应用(需要使用Stop If True there)

  2. 如果列E中单元格中的值小于列F单元格中的值,那么整行应具有绿色背景。 li>


我尝试过很多录音,但没有正确录制。



请帮助。

解决方案

这将为您提供简单的案例的答案,但是您可以展开关于您将如何知道哪些列需要进行比较(在这种情况下为B和C)以及初始范围( A1:D5 在这种情况下)将是?然后我可以尝试提供一个更完整的答案。

  Sub setCondFormat()
范围(B3)。选择
带范围(B3:H63)
.FormatConditions.Add类型:= xlExpression,Formula1:= _
= IF($ D3 =,FALSE,IF ($ F3> = $ E3,TRUE,FALSE))
With .FormatConditions(.FormatConditions.Count)
.SetFirstPriority
带.Interior
.PatternColorIndex = xlAutomatic
.Color = 5287936
.TintAndShade = 0
结束
结束
结束
结束子

注意:这是在Excel 2010中测试。



编辑:根据注释更新代码。 / p>

I have Range object called DistinationRange which contains reference to range B3:H63

I want to apply following two conditional formatting using Excel VBA code dynamically. (Because the range would not be same all the time)

  1. If Cell column D is blank, no formatting should be applied (Need to use Stop If True there)
  2. If Value in Cell of column E is lesser than value in cell of column F, that whole row should have green background.

I tried a lot using recording but it's not recording properly.

Kindly Help.

解决方案

This will get you to an answer for your simple case, but can you expand on how you'll know which columns will need to be compared (B and C in this case) and what the initial range (A1:D5 in this case) will be? Then I can try to provide a more complete answer.

Sub setCondFormat()
    Range("B3").Select
    With Range("B3:H63")
        .FormatConditions.Add Type:=xlExpression, Formula1:= _
          "=IF($D3="""",FALSE,IF($F3>=$E3,TRUE,FALSE))"
        With .FormatConditions(.FormatConditions.Count)
            .SetFirstPriority
            With .Interior
                .PatternColorIndex = xlAutomatic
                .Color = 5287936
                .TintAndShade = 0
            End With
        End With
    End With
End Sub

Note: this is tested in Excel 2010.

Edit: Updated code based on comments.

这篇关于使用Excel VBA代码进行条件格式化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆