【问题标题】:Loop over a range of cells which contains merged cells循环遍历包含合并单元格的单元格范围
【发布时间】:2018-01-18 22:12:36
【问题描述】:

我想检查给定范围内具有特定属性(例如特定颜色)的所有单元格是否不为空。

问题在于,在该范围内,有一些合并的单元格,它们的尺寸各不相同(所以,我不能只检测它们并系统地解决它们)。

有没有类似的 对于 Range([some range]) 中的每个单元格

合并后的单元格只给我一个单元格?

我试过了,它给了我标准单元格,这意味着合并的单元格被多次计算。并且单元格的内容仅分配给左上角单元格(因此,它会检测合并单元格中的空单元格)

我也想过偏移功能,但我认为它不会起作用(例如这里。黑色单元格是合并单元格):

【问题讨论】:

标签: vba excel


【解决方案1】:

您可以使用以下功能。我已经评论它来解释正在发生的事情,但本质上是:

  • 循环遍历给定范围内的所有单元格
  • 检查单元格是否是其MergeArea 中的第一个单元格。请注意,MergeArea 只是未合并的单元格本身。
  • 检查是否为空。
  • 如果为空,则打印一条调试语句,显示单元格的地址/它的MergeArea

代码:

Function EmptyTest(rng As Range) As Boolean
    EmptyTest = False ' Set to true if any cell in rng is empty
    Dim cell As Range
    For Each cell In rng
        ' Add your custom check here, e.g. for cell colour is black test do
        ' If cell.Interior.Color = RGB(0,0,0) Then 

        ' Check it is the first cell in MergeArea
        If cell.Address = cell.MergeArea.Cells(1).Address Then
            ' Check if it's empty
            If Len(cell.MergeArea.Cells(1).Value) = 0 Then
                EmptyTest = True
                ' Have the immediate window open to see debug statements
                Debug.Print "Range: " & cell.MergeArea.Address & " is empty."
            End If
        End If

        ' "End If" here if you added a custom check like the interior colour demo above.
    Next cell
End Function

例子:

在 VBA 编辑器中,调用

EmptyTest Range("A1:G4")

在即时窗口中输出*:

Range: $A$1:$B$4 is empty.
Range: $C$3 is empty.
Range: $G$4 is empty.

此函数还返回TrueFalse,具体取决于任何单元格是否为空。


*可以通过按Ctrl + G在VBA编辑器中打开即时窗口。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-11
    • 1970-01-01
    • 1970-01-01
    • 2015-01-07
    • 1970-01-01
    • 2020-01-30
    • 2014-09-25
    相关资源
    最近更新 更多