Excel 基于另一列合并Vba中的单元格

Excel 基于另一列合并Vba中的单元格,excel,vba,for-loop,merge,Excel,Vba,For Loop,Merge,我目前正在一个定期Excel仪表板上自动执行任务。所有的数据都是按照我想要的填写的,但在格式化上述仪表板时,我遇到了一个障碍。 其想法是根据列C单元格中的值合并列F单元格。到目前为止,我的代码只合并了前2个单元格,for循环继续运行,没有任何更改 我尝试了For循环和Do,直到I空循环无效 Dim consumerwb As Workbook Dim CellSlct As Range, cell As Range Set consumerwb = Workbooks("Consumer_V2.

我目前正在一个定期Excel仪表板上自动执行任务。所有的数据都是按照我想要的填写的,但在格式化上述仪表板时,我遇到了一个障碍。 其想法是根据
列C
单元格中的值合并列F单元格。到目前为止,我的代码只合并了前2个单元格,for循环继续运行,没有任何更改

我尝试了
For循环
Do,直到I空
循环无效

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`
我希望行
F
单元格(空)根据行C的值合并在一起:

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的前两次重复,之后停止工作

感谢您的帮助

  • 您可以使用
    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
演示:

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