VBA Excel:将条件格式应用于BLANK单元格

我正在尝试编写一个子过程,它将一些条件格式应用于Excel中的一系列单元格。 我有点卡住,所以我用macroslogging器。 但我不知道为什么它应用下面的公式,当我手动运行代码失败。

  • 我想要做的是将条件格式应用到范围内的空白单元格。
  • 我想让单元格颜色变灰
  • 范围是一个表格,表格被称为“表格1”。
  • 我需要在sub中这样做,因为表dynamic刷新。

下面是录制的macros不起作用,而是将格式应用到错误的单元格。 任何帮助纠正它将不胜感激

谢谢

Sub MacroTest() Range("Table1").Select 'The below formula is wrong but I can't figure out what it should be Selection.FormatConditions.Add Type:=xlExpression, Formula1:="=LEN(TRIM(D15))=0" With Selection.FormatConditions(1).Interior .PatternColorIndex = xlAutomatic .ThemeColor = xlThemeColorAccent2 .TintAndShade = 0.399945066682943 End With Selection.FormatConditions(1).StopIfTrue = False End Sub 

试试这个( 试过并testing过

更改

 Selection.FormatConditions.Add Type:=xlExpression, Formula1:="=LEN(TRIM(D15))=0" 

 Selection.FormatConditions.Add Type:=xlExpression, Formula1:= _ "=LEN(TRIM(C" & Range("Table1").Row & "))=0" 

所以你的代码可以写成

 Sub Sample() With ThisWorkbook.Sheets("Sheet1").Range("Table1") .FormatConditions.Add Type:=xlExpression, Formula1:= _ "=LEN(TRIM(C" & .Row & "))=0" .FormatConditions(.FormatConditions.Count).SetFirstPriority With .FormatConditions(1).Interior .PatternColorIndex = xlAutomatic .ThemeColor = xlThemeColorDark2 .TintAndShade = -9.99481185338908E-02 End With End With End Sub 

即使Sid已经有一个很好的答案,这是我的意见。 我重新创build了名称test表,并将其定位在A1 。 我使用了你的代码的一个小的编辑,它适合我。

 Sub Test() Dim v As Range Set v = Range("test") v.ClearFormats v.FormatConditions.Add Type:=xlExpression, Formula1:="=LEN(TRIM(A1))=0" With v.FormatConditions(1).Interior .PatternColorIndex = xlAutomatic .ThemeColor = xlThemeColorAccent2 .TintAndShade = 0.399945066682943 End With v.FormatConditions(1).StopIfTrue = False End Sub 

但是,正如注意到的那样,公式中A2的使用可能会产生不灵活的结果,特别是与Sid在上面的代码中使用的结果相比。

希望它有助于(或者至less提供一些见解)!

第二拍:

这一直困扰着我,因此我再来一次。 很显然,基于这个微软支持块 ,CF似乎存在问题。 存在两种解决方法:通过使用绝对引用或在应用CF之前先select单元格。

我玩了很多次,绝对参考了很多次。 但是,一个简单的方法是有效的 我们selectTable1的第一个单元格并给它CF,然后在书中使用最简单的方法:格式画家! 我们也用.ClearFormatsreplace了.FormatConditions.Delete

下面是上述方法的代码变体:

 Sub Test() Dim Table1 As Range: Set Table1 = ThisWorkbook.Sheets("Sheet1").Range("Table1") Start = Timer() Application.ScreenUpdating = False Table1.FormatConditions.Delete With Table1.Cells(2, 1) 'With Range("B7") .Select .FormatConditions.Add Type:=xlExpression, Formula1:= _ "=LEN(TRIM(B7))=0" .FormatConditions(.FormatConditions.Count).SetFirstPriority With .FormatConditions(1).Interior .PatternColorIndex = xlAutomatic .ThemeColor = xlThemeColorAccent2 .TintAndShade = 0.399945066682943 End With .FormatConditions(1).StopIfTrue = False .Copy End With Table1.PasteSpecial xlPasteFormats 'or the next one 'Range("B7:AO99").PasteSpecial xlPasteFormats Application.CutCopyMode = False Application.ScreenUpdating = True Debug.Print Timer() - Start End Sub 

这里是结果的预览。

示例表1

执行时间(以秒为单位)是:

  • 4.296875E-02
  • 4.492188E-02
  • 5.273438E-02
  • 5.859375E-02
  • 0.0625

这些比我以前的尝试要快得多,我在所有单元格中循环并将CF添加到每个单元格中。

希望这可以帮助你!