在VBA中连接,直到找到空单元格

时间:2018-05-25 15:37:21

标签: vba excel-vba excel

如何创建与","连接的所有第一个列号直到细胞是空的。然后从下一个非空单元格开始,代码应重复n = 1000个数字。

示例:

第一列编号包括

12
34
445
565

Here there is an empty cell in the 1st column

345
4767
765

结果:

12,34,445,565

345,4767,765

1 个答案:

答案 0 :(得分:0)

正如我在评论中所说的那样,与site

的建议相比,我会以不同的方式略微做到这一点
Option Explicit

Sub ConcatenateCells()

Const DELIMITER = ","
Dim rg As Range
Dim col As Collection
Dim vDat As Variant
Dim i As Long

    Set rg = Range("A1:A1000")
    vDat = WorksheetFunction.Transpose(rg)
    Set col = New Collection
    Dim colInp As String

    For i = LBound(vDat) To UBound(vDat)

        If Len(vDat(i)) = 0 And Len(colInp) > 0 Then
            col.Add colInp
            colInp = ""
        Else
            If Len(colInp) = 0 Then
                colInp = vDat(i)
            Else
                colInp = colInp & DELIMITER & vDat(i)
            End If
        End If

    Next i

    ' Output the result (collection) in the immediate window
    For i = 1 To col.Count
        Debug.Print col.Item(i)
    Next i

End Sub