连接数据列

时间:2016-01-16 18:20:00

标签: excel vba excel-vba concatenation

*已编辑添加:我收到的当前错误。有关屏幕截图,请参阅此帖的底部。

我在D列中有文字。宏应该找到空白单元格,然后连接下面所有单元格的文本。

示例

从D2开始的文字,显示如下......

Blank Cell
SampleText1
SampleText2
SampleText3
Blank Cell
SampleText4
SampleText5
SampleText6

显示D2 ...

中的文字
SampleText1, SampleText2, SampleText3

然后在D6中,像这样...

SampleText4, SampleText5, SampleText6

..等等。

这只需要在D列中工作,所以我猜我可以把它写到那个范围。

我遇到的最接近的答案是: Excel Macro to concatenate

以下是我目前正在使用的代码......

Sub ConcatColumns()

   Do While ActiveCell <> ""  'Loops until the active cell is blank.

      'The "&" must have a space on both sides or it will be
      'treated as a variable type of long integer.

      ActiveCell.Offset(0, 1).FormulaR1C1 = _
         ActiveCell.Offset(0, -1) & " " & ActiveCell.Offset(0, 0)

      ActiveCell.Offset(1, 0).Select
   Loop

End Sub

编辑:现在使用来自@jeeped的优秀代码但收到错误,如下面的屏幕截图所示

enter image description here

1 个答案:

答案 0 :(得分:1)

从底部开始并进行操作,构建一个字符串数组。当您到达空白单元格时,使用首选的分隔符Join字符串。

Sub build_StringLists()
    Dim rw As Long, v As Long, vTMP As Variant, vSTRs() As Variant
    Dim bReversedOrder As Boolean, dDeleteSourceRows As Boolean
    ReDim vSTRs(0)

    bReversedOrder = False
    dDeleteSourceRows = True

    With Worksheets("Sheet4")
        For rw = .Cells(Rows.Count, 1).End(xlUp).Row To 1 Step -1
            If IsEmpty(.Cells(rw, 1)) Then
                ReDim Preserve vSTRs(0 To UBound(vSTRs) - 1)
                If Not bReversedOrder Then
                    For v = LBound(vSTRs) To UBound(vSTRs) / 2
                        vTMP = vSTRs(UBound(vSTRs) - v)
                        vSTRs(UBound(vSTRs) - v) = vSTRs(v)
                        vSTRs(v) = vTMP
                    Next v
                End If
                .Cells(rw, 1) = Join(vSTRs, ", ")
                .Cells(rw, 1).Font.Color = vbBlue
                If dDeleteSourceRows  Then _
                    .Cells(rw, 1).Offset(1, 0).Resize(UBound(vSTRs) + 1, 1).EntireRow.Delete
                ReDim vSTRs(0)
            Else
                vSTRs(UBound(vSTRs)) = .Cells(rw, 1).Value2
                ReDim Preserve vSTRs(0 To UBound(vSTRs) + 1)
            End If
        Next rw
    End With

End Sub

我留下了用于反转字符串列表以及删除原始字符串行的选项。

build_String_Lists_before
在build_StringLists过程之前

build_String_Lists_After
在build_StringLists过程之后

相关问题