合并Excel中的单元格而不会丢失数据

时间:2013-09-13 11:11:15

标签: excel excel-vba merge excel-2007 vba

首先抱歉有关于此的新线程,但我无法在现有线程中发表评论。

我正在尝试合并很多单元格,就像在this线程中一样,但我对编码很新,尤其是excel / VBA,所以我不能让它工作。我有相同的场景(除了我没有任何空行)所以我只是尝试使用现有线程中的代码而不是真正理解语法:

Sub mergecolumn()

Dim cnt As Integer
Dim rng As Range
Dim str As String

For i = ActiveSheet.UsedRange.Rows.Count To 1 Step -1
cnt = Cells(i, 1).MergeArea.Count
Set rng = Range(Cells(i, 2), Cells(i - cnt + 1, 2))

For Each cl In rng
    If Not IsEmpty(cl) Then str = str + vbNewLine + cl
Next
If str <> "" Then str = Right(str, Len(str) - 2)

Application.DisplayAlerts = False
rng.Merge
rng = str
Application.DisplayAlerts = True

str = ""
i = i - cnt + 1
Next i

End Sub

我试图以不同的方式运行宏来标记多个列,标记多行并标记一些区域,但我总是得到:

运行时错误'13':
类型不匹配

当我进入调试屏幕时,标记为:

str = str + vbNewLine + cl

我通过Developer-ribbon-&gt; Visual Basic-&gt; Insert-&gt;模块添加了宏,只是将代码粘贴到那里并保存。

提前感谢您提供任何帮助 //乔金姆

1 个答案:

答案 0 :(得分:2)

以下是代码的两个版本。

VER 1 (不会忽略空单元格)

'~~> For Group MERGING (Merge Cells and Keep All text)
Public Sub Sample()
    On Error GoTo ErrMergeAll

    Application.DisplayAlerts = False

    Dim Cl As Range
    Dim strTemp As String

    '~~> Collect values from all the cells and separate them with spaces
    For Each Cl In Selection
        If Len(Trim(strTemp)) = 0 Then
            strTemp = strTemp & Cl.Value
        Else
            strTemp = strTemp & vbNewLine & Cl.Value
        End If
    Next

    strTemp = Trim(strTemp)

    '~~> Merging of cells
    With Selection
        .HorizontalAlignment = xlCenter
        .VerticalAlignment = xlCenter
        .MergeCells = False
    End With
    Selection.Merge

    '~~> Set new value of the range
    Selection.Value = strTemp

    Application.DisplayAlerts = True
    Exit Sub

ErrMergeAll:
    MsgBox Err.Description, vbInformation
    Application.DisplayAlerts = True
End Sub

VER 2 (忽略空白单元格)

'~~> For Group MERGING (Merge Cells and Keep All text)
Public Sub Sample()
    On Error GoTo ErrMergeAll

    Application.DisplayAlerts = False

    Dim Cl As Range
    Dim strTemp As String

    '~~> Collect values from all the cells and separate them with spaces
    For Each Cl In Selection
        If Len(Trim(Cl.Value)) <> 0 Then
            If Len(Trim(strTemp)) = 0 Then
                strTemp = strTemp & Cl.Value
            Else
                strTemp = strTemp & vbNewLine & Cl.Value
            End If
        End If
    Next

    strTemp = Trim(strTemp)

    '~~> Merging of cells
    With Selection
        .HorizontalAlignment = xlCenter
        .VerticalAlignment = xlCenter
        .MergeCells = False
    End With
    Selection.Merge

    '~~> Set new value of the range
    Selection.Value = strTemp

    Application.DisplayAlerts = True
    Exit Sub

ErrMergeAll:
    MsgBox Err.Description, vbInformation
    Application.DisplayAlerts = True
End Sub

<强> SCREENSHOT

enter image description here

相关问题