循环遍历包含合并单元格的一系列单元格

时间:2017-08-10 15:10:53

标签: excel vba excel-vba

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

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

有什么相似的吗? 对于范围中的每个单元格([某个范围])

这会给我一个合并单元格的单元格吗?

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

我也考虑了偏移功能,但我认为它不会起作用(例如这里。黑色单元格是合并的单元格): Black cells are merged

1 个答案:

答案 0 :(得分: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

示例:

sheet

在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编辑器中打开即时窗口。