我有以下一组数据:
Col A Col B
Prod1 SKU-A, SKU-B
Prod2 SKU-C, SKU-D, SKU-E
我需要将其输出为:
Col A Col B Col C
Prod1 SKU-A 1
Prod1 SKU-B 2
Prod2 SKU-C 1
Prod2 SKU-D 2
Prod2 SKU-E 3
基本上我需要将 B 列中逗号分隔的值拆分成单独的行,我认为我可以通过本网站上提供的各种宏来实现,然而我需要添加(另一个)C 列,为 A 列中给出的每个产品的每个拆分行分配一个数字序列。
我希望这是有道理的!
编辑在 VBA 中添加我正在使用:
Sub SliceNDice()
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
[c1].Resize(lngCnt, 2).Value2 = Application.Transpose(Y)
End Sub
如果您需要任何其他详细信息,请告诉我,提前谢谢您:-)
答案1
使用列中的数据A和乙,运行这个简短的宏将在列中产生所需的输出C通过埃
Sub reorg()
Dim i As Long, N As Long
Dim K As Long, KK As Long
N = Cells(Rows.Count, 1).End(xlUp).Row
K = 1
For i = 1 To N
prod = Cells(i, 1).Value
ary = Split(Cells(i, 2).Value, ", ")
For KK = LBound(ary) To UBound(ary)
Cells(K, 3).Value = prod
Cells(K, 4).Value = ary(KK)
Cells(K, 5).Value = KK + 1
K = K + 1
Next KK
Next i
End Sub