在Excel中将一列中的不同行数连接起来

时间:2016-05-13 11:48:11

标签: excel excel-vba concat vba

你能帮我理解如何在一列中连接一堆记录的所有行,但行数不同,并用关键字描述第一行,如'File *#'?一个例子:

1   file# x  stuff...  
2   more stuff  
3   more stuff.   
4   file# x   stuff...  
5   more stuff  
6   File #    stuff  
7   File#   stuff

谢谢!

1 个答案:

答案 0 :(得分:0)

可能有更好的方法,但我认为这对您有用:

Sub Test()

Dim r As Range
Dim i As Integer
Dim lRow As Long
Dim x As Variant
Dim arr() As Variant
Dim aSht As Worksheet

Set aSht = ActiveSheet
Set r = ActiveSheet.Range("A1")
i = 1
Do While r <> ""
    If Left(r.Offset(i, 0), 6) = "File #" Or r.Offset(i, 0) = "" Then
        x = r.Resize(i, 1).Value2
        ReDim arr(1 To UBound(x, 1))
        For lRow = 1 To UBound(x, 1)
            arr(lRow) = x(lRow, 1)
        Next
        If aSht.Cells(aSht.Rows.Count, 2).End(xlUp).Value = "" Then
            aSht.Cells(aSht.Rows.Count, 2).End(xlUp).Value = Join(arr, ";")
        Else
            aSht.Cells(aSht.Rows.Count, 2).End(xlUp).Offset(1, 0).Value = Join(arr, ";")
        End If
        Set r = r.Offset(i, 0)
        i = 1
    Else
        i = i + 1
    End If
Loop

End Sub

注意:文件必须至少有2行。换句话说,第1行是File ...,第2行是stuff。每个文件行必须开始:File(空格)#。我可以使它更灵活,但它可以正常工作。