【问题标题】:How to concatenate selected columns into one column?如何将选定的列连接成一列?
【发布时间】:2020-08-02 23:22:21
【问题描述】:

我正在尝试连接选定的列并将连接写入选定的列中。

例如,我有 A、B、C、D、E 列,每列有五行。我想要一个 InputBox 来选择整个列,或者列的第一个单元格,然后遍历所有剩余的单元格并将结果放在另一个选择范围/列的第一个单元格中。

如果我选择 A 列/单元格 A1 和 C 列/单元格 C1 和 F 列作为目标范围,它将帮助我循环 A1 到 A5 和 C1 到 C5 并将结果放入 F1(A1&C1) 到 F5( A5&C5)。

我为单个单元格找到了类似的东西,但没有进行循环。

Sub MergeCells()

    Dim xJoinRange As Range
    Dim xDestination As Range

    Set xJoinRange = Application.InputBox(prompt:="Highlight source cells to merge", Type:=8)
    Set xDestination = Application.InputBox(prompt:="Highlight destination cell", Type:=8)
    temp = ""
    For Each Rng In xJoinRange
        temp = temp & Rng.Value & " "
    Next
    xDestination.Value = temp
End Sub

【问题讨论】:

  • 你能连接任意数量的列吗?
  • 是的,这就是我想要的。这取决于用户选择列的任意组合。

标签: excel vba


【解决方案1】:

在下面试试这个。这个概念是通过使用Intersect 函数逐行查看该行中是否需要输出。另外,检查该行中是否有任何选择加入。即使选择了多列,也只会写入目标范围的第一列。

    Sub MergeCell2()

    Dim xJoinRange As Range
    Dim xDestination As Range

    Set xJoinRange = Application.InputBox(prompt:="Highlight source cells to merge", Type:=8)
    Set xDestination = Application.InputBox(prompt:="Highlight destination cell", Type:=8)

     ' find 1st and last row

    Dim iRow1 As Long, iRowLast As Long
    Dim Rng As Variant

    iRow1 = 9999999
    iRowLast = 0

    For Each Rng In xJoinRange
        If Rng.Row < iRow1 Then iRow1 = Rng.Row
        If Rng.Row > iRowLast Then iRowLast = Rng.Row
    Next

    Dim rThisRange As Range
    Dim rDestCell As Range
    Dim i As Long
    Dim temp As Variant

    For i = iRow1 To iRowLast
        Set rDestCell = Intersect(xDestination, Rows(i))  ' see if output is required in this row
        If Not rDestCell Is Nothing Then
            Set rThisRange = Intersect(xJoinRange, Rows(i)) ' see if anything is selected in this row
            If Not rThisRange Is Nothing Then
                temp = ""
                For Each Rng In rThisRange
                    temp = temp & Rng.Value & " "
                Next
                rDestCell(1).Value = temp  ' (1) to write only the 1st column of dest range
            End If
        End If
    Next

End Sub

【讨论】:

    猜你喜欢
    • 2019-07-04
    • 2016-02-13
    • 1970-01-01
    • 2023-02-25
    • 1970-01-01
    • 1970-01-01
    • 2018-08-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多