根据另一列合并Vba中的单元格

时间:2019-09-04 04:32:36

标签: excel vba for-loop merge

我目前正在重复执行Excel Dashboard上的任务。所有数据都根据我想要的内容填写,但在格式化所述仪表板时遇到了障碍。 想法是根据column C单元格中的值合并F列单元格。到目前为止,我的代码仅合并了前2个单元格,并且for循环继续进行而不改变任何内容。

我尝试了For LoopDo until Isempty循环均无济于事。

Dim consumerwb As Workbook
Dim CellSlct As Range, cell As Range
Set consumerwb = Workbooks("Consumer_V2.xlsm")
consumerwb.Activate

Set CellSlct = Range("C6").End(xlDown)

Mergeagain:

On Error Resume Next

For Each cell In CellSlct
 If cell.Value = cell.Offset(1, 0).Value And IsEmpty(cell) = False Then
        Range(cell.Offset(0, 3), cell.Offset(1, 3)).Merge
        GoTo Mergeagain
 End If  
Next`

我希望根据C行的值将F行单元(空)合并到一起:

C           D  E  F
customer1   X  X  Cst1
customer2   X  X  Cst2
customer2   X  X  (Merged with above, this is where my code stops merging)
customer2   X  X  (Merged with above)
customer3   X  X  Cst3
customer3   X  X  (Merged with above)

F列完全为空,到目前为止,我的代码合并了Customer2的前2个重复项,此后停止工作...

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

  • 您可以使用Union创建合并之前要合并的范围。然后使用功能Range.Merge合并它们。

  • 这将在问题中从C6开始连续运行。您可以根据自己的目的操纵代码。

尝试一下:

Sub Mrg()

Dim consumerwb As Workbook
Dim CellSlct As Range, cel As Range
Set consumerwb = Workbooks("Consumer_V2.xlsm")
consumerwb.Activate

Set CellSlct = Range("C6").Offset(0, 3)

For Each cel In Range("C7:C" & Range("C6").End(xlDown).row)

    If cel.Value = cel.Offset(-1, 0).Value Then
       Set CellSlct = Union(CellSlct, cel.Offset(0, 3))
    Else
        CellSlct.Merge
        Set CellSlct = cel.Offset(0, 3)
    End If

Next

CellSlct.Merge

End Sub

演示:

enter image description here

相关问题