取消合并和填充值 - 如果单元格合并到同一列

时间:2018-02-06 16:53:26

标签: vba excel-vba excel

我有一个VBA代码,它取消合并单元格并填充这些单元格的值。

我希望只有当合并的单元格属于同一列时才会填充值。

Sub UnMergeFill()

    Dim cell As Range, joinedCells As Range

    For Each cell In ThisWorkbook.ActiveSheet.UsedRange
        If cell.MergeCells Then
            Set joinedCells = cell.MergeArea
            cell.MergeCells = False
            ' I need an if loop here to check if the Range happens to be in the same column
            joinedCells.Value = cell.Value
        End If
    Next

    End Sub

例如,我希望所有单元格都未合并。但是只需要将Test2值拖动到那些单元格,因为它们都属于同一列。测试值不应该跨越不同的列。

Sample Here

1 个答案:

答案 0 :(得分:2)

Option Explicit

Sub UnMergeFill()

    Dim cell            As Range
    Dim joinedCells     As Range
    Dim MultiCol        As Boolean

    For Each cell In ThisWorkbook.ActiveSheet.UsedRange
        If cell.MergeCells Then

            '/ Multiple columns?
            If cell.MergeArea.Columns.Count <= 1 Then
                MultiCol = False
            Else
                MultiCol = True
            End If

            Set joinedCells = cell.MergeArea
            cell.MergeCells = False

            '/ Only when all the cells are in same column
            If Not MultiCol Then
                joinedCells.Value = cell.Value
            End If
        End If
    Next

End Sub