【问题标题】:Clear contents of cell range with merged cells based on Interior.Color使用基于 Interior.Color 的合并单元格清除单元格范围的内容
【发布时间】:2021-08-19 15:20:57
【问题描述】:

我有一些 VBA 可以根据单元格的颜色清除指定范围内的单元格。这些细胞是硬色的。它可以在没有未合并单元格的情况下工作,但是一旦我在范围内添加合并单元格,它就会失败。

我一直在做一些挖掘,似乎我需要使用 Cells 来引用合并中的第一个单元格。由于我对 VBA 不熟悉,所以不知道如何合并这两段代码。

如果您能提供任何帮助、建议或指向其他解决方案的链接,我们将不胜感激。

当前有效的代码:

Sub ClearContentByBackground()
For Each Cell In Range("b1:i32")
    If Cell.Interior.Color = RGB(226, 239, 218) Then
        Cell.ClearContents
    End If
Next
End Sub

Code that I found during my search:

If Cells(j, l).MergeCells Then
    Cells(j, l).MergeArea.ClearContents
Else
    Cells(j, l).ClearContents
End If

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    试试这个:

    Option Explicit
    
    Sub ClearContentByBackground()
        Dim cell As Range
        For Each cell In Range("b1:i32")
            If cell.Interior.Color = RGB(226, 239, 218) Then
                cell.MergeArea.ClearContents
            End If
        Next
    End Sub
    

    如果单元格是合并范围的一部分,则必须清除 MergedArea 的内容。 如果单元格不是合并范围的一部分,则必须清除一个单元格的内容。由于这样一个单元格的cell.MergeArea 属性等于该单元格本身,所以这里的条件If Cells(j, l).MergeCells Then 是多余的。

    【讨论】:

      猜你喜欢
      • 2016-01-15
      • 1970-01-01
      • 2017-07-24
      • 2018-07-08
      • 2012-11-10
      • 1970-01-01
      • 2013-09-03
      • 1970-01-01
      相关资源
      最近更新 更多