简体   繁体   English

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

[英]VBA Excel: Apply conditional formatting to BLANK cells

I'm trying to write a sub procedure which applies some conditional formatting to a range of cells in Excel. 我正在尝试编写一个子过程,该过程将一些条件格式应用于Excel中的一系列单元格。 I'm getting a bit stuck so I used the Macro recorder. 我有点卡住了,所以我使用了宏录制器。 I can't however figure out why it's applying the formula below and when I run the code manually it fails. 但是,我无法弄清楚为什么它要使用下面的公式,而当我手动运行代码时,它会失败。

  • What I want to do is apply conditional formatting to the blank cells in the range. 我要做的是将条件格式应用于该范围内的空白单元格。
  • I want to make the cell color grey 我想将单元格颜色设为灰色
  • The range is a table and the table is called 'Table1'. 范围是一个表,该表称为“ Table1”。
  • I need to do this in a sub because the table refreshes dynamically. 我需要在子目录中执行此操作,因为表会动态刷新。

Below is the recorded macro which doesn't work and instead applies formatting to the wrong cells. 下面是录制的宏,该宏不起作用,而是将格式应用于错误的单元格。 Any help correcting it would be appreciated 任何帮助纠正它将不胜感激

Thanks 谢谢

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

Try this ( Tried and tested ) 试试这个( 尝试并测试

Change 更改

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

to

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

So your code can be written as 所以你的代码可以写成

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

Here's my take, even if Sid already has a great answer. 即使Sid已经有了很好的答案,这也是我的看法。 I recreated a table with name test and positioned it at A1 . 我用名称test重新创建了一个表,并将其放置在A1 I used a minor edit of your code and it works fine for me. 我对您的代码进行了少量编辑,对我来说很好用。

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

Just as a note, though, the usage of A2 inside the formula can produce inflexible results, especially compared to what Sid used in his code above. 就像需要注意的那样,在公式中使用A2可能会产生不灵活的结果,特别是与Sid在上面的代码中使用的结果相比。

Hope it helps (or at least gives some insight)! 希望它可以帮助(或至少提供一些见识)!

SECOND TAKE: 第二步:

This has been bothering me since the other day so I'll give it another shot. 从前一天开始,这一直困扰着我,所以我再给它一个镜头。 Apparently, based on this Microsoft Support nugget , there seems to be issues with CF as it is. 显然,基于此Microsoft支持小组 ,CF本身似乎存在问题。 Two workarounds exist: either by using absolute reference or by selecting the cell first before applying CF. 存在两种解决方法:通过使用绝对引用或通过在应用CF之前先选择单元格。

I played around a bit and got wrong results a lot of times with absolute reference. 我打了一些球,在绝对参考下很多次都得到了错误的结果。 However, one simple approach works. 但是,一种简单的方法有效。 We select the first cell of Table1 and give it CF, and then we use the simplest approach in the book: format painter! 我们选择Table1的第一个单元格并将其赋予CF,然后使用书中最简单的方法:format painter! We also replaced .ClearFormats with .FormatConditions.Delete . 我们还将.ClearFormats替换为.FormatConditions.Delete

Here's a variation of your code with the aforementioned approach: 这是上述方法的代码变体:

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

Here's a preview of results. 这是结果预览。

样本表1

Execution times (in seconds) are: 执行时间(以秒为单位)为:

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

These are much faster than a previous attempt of mine where I looped through all the cells and added CF to each. 这些速度比我以前的尝试要快得多,在我的尝试中,我遍历了所有单元格并将CF添加到每个单元格中。

Hope this helps you! 希望这对您有所帮助!

After some searching I found an option that works without using the function LEN and needing to specify the range using the xlBlanksCondition. 经过一些搜索后,我发现了一个无需使用功能LEN即可工作且需要使用xlBlanksCondition指定范围的选项。 I do not why the macro recorder comes up with the LEN solution if it also could have used the xlBlanksCondition solution. 如果宏记录器也可以使用xlBlanksCondition解决方案,那么我不解释为什么宏记录器会提供LEN解决方案。

Source: MSDN Microsoft 资料来源: Microsoft MSDN

I first select a range and then I apply this code: 我首先选择一个范围,然后应用以下代码:

With Selection.FormatConditions.Add(Type:=xlBlanksCondition)
    .StopIfTrue = False
    .Interior.PatternColorIndex = xlAutomatic
    .Interior.Color = RGB(226, 80, 80)
    .Interior.ThemeColor = xlThemeColorAccent2
    .Interior.TintAndShade = 0.39
    .Font.Color = vbBlack
    .Font.TintAndShade = 0
    .Borders.LineStyle = xlContinuous
    .Borders.TintAndShade = 0
    .Borders.Weight = xlThin
    .Borders.Color = RGB(255, 0, 0)
    .StopIfTrue = False
End With

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

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