【问题标题】:Concatenate multiple cells in a selection into a single string cell with newline/carriage returns使用换行符/回车符将选择中的多个单元格连接成单个字符串单元格
【发布时间】:2016-12-21 02:14:59
【问题描述】:

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

例如选择图片:

连接后应该是这样的:

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

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

【问题讨论】:

    标签: excel vba


    【解决方案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
    

    【讨论】:

    • 嘿 nightcrawler,如何将输出写入同一个工作簿中的不同工作表,以便保留原始数据?我试过工作表。激活....
    【解决方案2】:

    这是另一个尝试:

    之前:

    一些代码:

    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
    

    之后:

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

    【讨论】:

    • 这将适用于 2 列选择,而不是任何数量的列。 :)
    猜你喜欢
    • 2013-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-11
    • 1970-01-01
    • 1970-01-01
    • 2018-03-23
    相关资源
    最近更新 更多