简体   繁体   English

循环通过VBA中的合并单元格

[英]Looping through Merged cells in VBA

Is it possible to loop through merged cells in . 是否可以在循环合并的单元格。

  • I have 6 merged cells in the range B4:B40 我在B4:B40范围内有6个合并的单元格
  • I need the values in these 6 cells 6 iterations only. 我只需要6个单元格中的6个迭代值。

The above answers look to have you sorted. 上面的答案看起来让你排序。

If you don't know where the merged cells are then you can use the following routine to quickly detect them. 如果您不知道合并单元格的位置,则可以使用以下例程快速检测它们。

When I built Mappit! 当我建立Mappit! I realised that when I developed merged cell reporting that merged cells were part of xlBlanks 我意识到,当我开发合并的单元格报告时,合并的单元格是xlBlanks一部分

So you can use the code to detect merged cells immediately rather than loop through each cell testing for the MergedCells property being true. 因此,您可以使用代码立即检测合并的单元格,而不是循环遍历每个单元格测试,以MergedCells属性为true。

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

Here is a first stab to your issue: 以下是对您的问题的第一次尝试:

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

Just a little tighter, similar idea: 只是更紧凑,类似的想法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM