显示以逗号分隔的第二列作为子类别

时间:2015-04-21 14:25:42

标签: excel vba excel-vba excel-2010

有没有办法将列B用逗号分隔的数据转换为多行,也可以作为列A的子类别,其值是唯一的。

示例:

   A        B
1      222,333,444
2      111,222,333

转换为

    A       B
1          222
_          333
_          444
2          111
_          222
_          333

_是一个单独的行

1 个答案:

答案 0 :(得分:1)

这将用换行符取代昏迷

Dim lastRow As Integer
lastRow = Sheets("Sheet1").Range("B1").End(xlDown).Row
For i = 1 To lastRow

    Sheets("Sheet1").Cells(i, 2).Replace ",", vbCrLf
    Sheets("Sheet1").Cells(i, 2).Range("B1").Rows.AutoFit
Next

编辑:这应该符合您的要求

Dim objRegex As Object
Dim X
Dim Y
Dim lngRow As Long
Dim lngCnt As Long
Dim tempArr() As String
Dim strArr
Set objRegex = CreateObject("vbscript.regexp")
objRegex.Pattern = "^\s+(.+?)$"
 'Define the range to be analysed
X = Range([a1], Cells(Rows.Count, "b").End(xlUp)).Value2
ReDim Y(1 To 2, 1 To 1000)
For lngRow = 1 To UBound(X, 1)
     'Split each string by ","
    tempArr = Split(X(lngRow, 2), ",")
    For Each strArr In tempArr
        lngCnt = lngCnt + 1
         'Add another 1000 records to resorted array every 1000 records
        If lngCnt Mod 1000 = 0 Then ReDim Preserve Y(1 To 2, 1 To lngCnt + 1000)
        Y(1, lngCnt) = X(lngRow, 1)
        Y(2, lngCnt) = objRegex.Replace(strArr, "$1")
    Next
Next lngRow
 'Dump the re-ordered range to columns C:D
[a1].Resize(lngCnt, 2).Value2 = Application.Transpose(Y)

我测试了它,这是我的输出。如果有问题,请告诉我。

enter image description here