【发布时间】:2012-02-22 08:04:23
【问题描述】:
是否可以循环遍历vba中的合并单元格。
-
B4:B40范围内有 6 个合并单元格 - 我只需要这 6 个单元格中的值 6 次迭代。
【问题讨论】:
-
你知道合并了多少个单元格吗?为什么只需要 6 次迭代?您能否向我们解释一下您打算做什么?
是否可以循环遍历vba中的合并单元格。
B4:B40 范围内有 6 个合并单元格
【问题讨论】:
上面的答案看起来你已经排序了。
如果您不知道合并单元格的位置,则可以使用以下例程快速检测它们。
当我构建 Mappit! 时,我意识到当我开发合并单元格报告时,合并单元格是 xlBlanks 的一部分
因此,您可以使用代码立即检测合并的单元格,而不是循环遍历每个单元格来测试 MergedCells 属性是否为真。
Sub DetectMerged()
Dim rng1 As Range
Dim rng2 As Range
On Error Resume Next
Set rng1 = Intersect(Cells.SpecialCells(xlFormulas), Cells.SpecialCells(xlBlanks))
Set rng2 = Intersect(Cells.SpecialCells(xlConstants), Cells.SpecialCells(xlBlanks))
On Error GoTo 0
If Not rng1 Is Nothing Then MsgBox "Merged formulae cells in " & rng1.Address(0, 0)
If Not rng2 Is Nothing Then MsgBox "Merged constant cells in " & rng2.Address(0, 0)
End Sub
【讨论】:
这是您的问题的第一次尝试:
Option Explicit
Sub loopOverCells()
Dim rCell As Range
Dim i As Integer
Set rCell = [B1]
For i = 1 To 6
Debug.Print rCell.Address
Set rCell = rCell.Offset(1, 0) ' Jump 1 row down to the next cell
Next i
End Sub
【讨论】:
Offset() 的工作原理,说它跳转到分组单元格的下一项而不是说跳到下一个单元格可能更准确。你觉得 JMax 怎么样?
只是更紧凑一点,类似的想法:
Option Explicit
Sub ListValues()
Dim i As Long
For i = 4 To 40 Step 6
Debug.Print Range("B" & i).Value
Next i
End Sub
【讨论】: