连接和迭代多个单元VBA excel

时间:2013-11-27 11:29:43

标签: excel vba excel-vba excel-2007

我想迭代存储在不同单元格中的数据(类似于下面所示的数据),并将它们组合成一个由新行分隔的单个单元格(chr(10))。 需要导入一个单元格的数据量会发生变化。

2991
19391
423
435
436

无论是否有任何换行符,代码都需要遍历整个工作表。所需格式为:

    2991 - all three cells would be combined into one cell in the next column to this one.
    19391
    423
-Line space, this will need to be taken into account and is the seperator of data.
    26991 - all four cells would be combined into one cell in the next column to this one.
    19331
    424
    6764

下面是我到目前为止所获得的内容,它将当前行的左边的列合并,这是错误的。

Sub ConcatColumns()

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

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

      ActiveCell.Offset(1, 0).Select
   Loop

End Sub

2 个答案:

答案 0 :(得分:2)

我认为这可以使用UDF来完成。

这样的东西
Public Function JoinValues(rng As Range) As String

Dim cell As Range
Dim str As String

    For Each cell In rng
        If cell.Value <> "" Then
        str = str & cell.Value & Chr(10)
        End If
    Next cell

If Len(str) > 1 Then JoinValues = Left(str, Len(str) - 1)

End Function

然后在单元格中使用=JoinValues(A1:A10)来连接值。您还必须更改目标单元格中​​的单元格格式,以允许包装文本以使其正常工作。


假设您的值从单元格A2开始,请输入

=IF(A1="",joinvalues(OFFSET(A2,0,0,MATCH(TRUE,INDEX(ISBLANK(A2:A10000),0,0),0)-1)),"") 
在B2中

并向下拖动该功能。

答案 1 :(得分:2)

enter image description here

您可以使用此代码

来实现上述目标
Sub Main()

    Dim i As Long
    Dim c As Range
    For i = Range("A" & Rows.Count).End(xlUp).Row To 1 Step -1

        Dim strBuilder As String
        Set c = Range("A" & i)

        If Not IsEmpty(c) And i <> 1 Then
            strBuilder = c & Chr(10) & strBuilder
        ElseIf i = 1 Then
            strBuilder = c & Chr(10) & strBuilder
            c.Offset(0, 1) = Left(strBuilder, Len(strBuilder) - 1)
            strBuilder = vbNullString
        Else
            c.Offset(1, 1) = Left(strBuilder, Len(strBuilder) - 1)
            strBuilder = vbNullString
        End If

    Next i

End Sub