Excel操作
单元格合并,并保留全部值
2017-04-22 14:02:38

我们在做表格的时候,为了美观。遇到标题一般都会合并单元格、但是合并单元格只会加载一个单元格的值。 

如果合并选择的单元格区域,并要求保留选择的单元格内的值呢。如下表所示:

因为Excel默认的操作是当合并多个有内容的单元格时,只能保存左上角单元格的数据,会弹出下面的提示对话框:

过程代码

' 先选定需要合并的区域;

Sub MergerSelectedCells()

    Application.DisplayAlerts = False

    Dim allstr As String

    Dim Str As Object

    For Each Str In Selection

        If Str.Value <> "" Then

            allstr = allstr & " " & Str.Value

            allstr = Application.WorksheetFunction.Trim(allstr)

        End If

    Next Str

    With Selection

        .MergeCells = True

        .Value = allstr

        .WrapText = True

        .HorizontalAlignment = xlGeneral

        .VerticalAlignment = xlTop

    End With

    Application.DisplayAlerts = True

End Sub

代码分析

用一个For Each循环将选择区域Selection对象的每一个单元格的值逐一连接到一个字符串;

对选择区域应用合并属性(Selection.MergeCells),并将连接好的字符串赋值给它。

执行效果