简体   繁体   English

Excel VBA-如何在条件格式中忽略空白单元格

[英]Excel VBA - How to ignore blank cells in conditional formatting

I am trying to highlight cells that have a date less than today's date. 我试图突出显示日期小于今天的日期的单元格。 However, when applying conditional format, "ALL" blank cell's are highlighted. 但是,当应用条件格式时,“ ALL”空白单元格将突出显示。 I am aware of specifying the range (I2:I200), but the report is run on a daily basis which can consist of 1 to 200+. 我知道要指定范围(I2:I200),但是该报告每天运行,可能包含1到200+。 This is why I need the entire column formatted. 这就是为什么我需要格式化整个列的原因。

Sheets("Sheet1").Columns("I:I").Select
Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlLessEqual, Formula1:="=today()"
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1).Interior
    .PatternColorIndex = xlAutomatic
    .ThemeColor = xlThemeColorAccent2
    .TintAndShade = 0.399945066682943
End With
Selection.FormatConditions(1).StopIfTrue = False

Just an additional point: 只是一点:

The solution does not work if any of the dates are produced by formulas. 如果任何日期由公式产生,则该解决方案不起作用。

If you want to highlight date constants and date formulas, you need to go back to the original selection (or do the same thing by assigning a range): 如果要突出显示日期常量和日期公式,则需要返回到原始选择(或通过分配范围来执行相同的操作):

Sheets("Sheet1").Columns("I:I").Select

... and replace the conditional format with something like this: ...,然后将条件格式替换为以下内容:

Selection.FormatConditions.Add Type:=xlExpression, Formula1:="=if(isblank(i1),false,i1<=today())"

(I'm not expert at conditional formatting, so I don't really understand why it works when you refer to the first cell in the range, but it did when I tested it.) (我不是条件格式专家,所以当您引用范围中的第一个单元格时,我并不真正理解它为什么起作用,但是在我测试它时它确实起作用。)

You can use a SpecialCells() type. 您可以使用SpecialCells()类型。 The first line is all I changed. 第一行是我所做的全部更改。

Sheets("Sheet1").Columns("I:I").SpecialCells(xlCellTypeConstants).Select
Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlLessEqual, Formula1:="=today()"
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1).Interior
    .PatternColorIndex = xlAutomatic
    .ThemeColor = xlThemeColorAccent2
    .TintAndShade = 0.399945066682943
End With
Selection.FormatConditions(1).StopIfTrue = False

However, you should also avoid using .Select . 但是,还应避免使用.Select I'll leave how to do that as an exercise for the reader. 我将把如何做作为练习留给读者。

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

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