使用换行符/回车符将选定内容中的多个单元格连接到单个字符串单元格中

时间:2016-12-21 02:15:00

标签: excel vba

我需要将多行选择中的多个单元格连接成一个带有换行符/回车符的单个字符串单元格

e.g。选择图片:

enter image description here

连接后应该如下所示:

enter image description here

我的代码连接到一个单元格但没有添加换行符:

Sub concat_3()
    Dim row As Range
    Dim cell As Range
    Dim txt As String

    For Each row In Selection
        For Each cell In row.Cells
            txt = txt & cell.Value
        Next cell
        txt = txt & vbCrLf
    Next row
    Selection.ClearContents
    txt = Left(txt, Len(txt) - 2)
    Selection(1).Value = txt
End Sub

2 个答案:

答案 0 :(得分:1)

我用For循环编辑你的代码(不是For Each),它对我有用。尝试。

Sub concat_3()
    Dim c As Range
    Dim txt As String

    Dim i As Integer
    Dim j As Integer

    Set c = Selection
    txt = ""
    For i = 1 To c.Rows.Count
        For j = 1 To c.Columns.Count
            txt = txt & c(i, j).Value
        Next j
        txt = txt & vbCrLf
    Next i

    txt = Left(txt, Len(txt) - 2)
    'to output in Sheet1 A1
    Sheets("Sheet1").Range("A1") = txt
End Sub

答案 1 :(得分:0)

这是另一回事:

在:

enter image description here

一些代码:

Sub fhuscvc()
    Dim s As String, i As Long, a As Range
    i = 0
    s = ""

    For Each a In Selection
        s = s & "    " & a.Value
        i = i + 1
        If i = 2 Then
            i = 0
            s = s & vbCrLf
        End If
    Next a

    Selection.Clear
    Selection(1).Value = s
End Sub

之后:

enter image description here

分隔每对项目的固定空格块并不漂亮......太糟糕了 TAB 字符在单元格内不起作用。