循环遍历包含合并单元格的单元格区域

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

问题是,在这个范围内,有一些合并的单元格,而且这些单元格的尺寸是不同的(所以我不能仅仅检测它们并且系统地解决它们)。

有没有像范围内的每个单元格([某些范围])

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

我试了一下,它给了我标准单元格,这意味着合并的单元格不止一次地被计算在内。 而单元格的内容只分配给左上angular的单元格(所以,它会检测合并单元格中的空单元格)

我也考虑过偏移函数,但是我不认为它会起作用(例如这里,黑色单元格是合并的单元格): 黑细胞合并

您可以使用下面的function。 我已经评论它解释发生了什么,但基本上:

  • 遍历给定范围内的所有单元格
  • 检查单元格是否是其MergeArea的第一个单元格。 请注意, MergeArea只是单元格本身,如果不合并。
  • 检查是否空。
  • 如果为空,则显示debugging语句,显示单元格/其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, eg 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取决于任何单元是否为空。


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