输入是多列
<- A -> <- B> < -C-> <- D-> <- E >
1 Cat1 date1 a x,y,z a,b,c
2 Cat2 date2 b r,s e,f
3 Cat3 date3 c p,q g,h
4 Cat4 date4 d x,y i,j
=============================================== =========================
我正在使用以下代码:
Sub ExpandData()
Const FirstRow = 1
Dim LastRow As Long
LastRow = Range("A" & CStr(Rows.Count)).End(xlUp).Row
' Get the values from the worksheet
Dim SourceRange As Range
Set SourceRange = [A1].CurrentRegion
' Get sourcerange values into an array
Dim Vals() As Variant
Vals = SourceRange.Value
' Loop through the rows in the array and split each comma-delimited list of items and put each on its own row
Dim ArrIdx As Long
Dim RowCount As Long
For ArrIdx = LBound(Vals, 1) To UBound(Vals, 1)
Dim CurrCat As String
CurrCat = Vals(ArrIdx, 1)
Dim CurrList As String
CurrList = Replace(Vals(ArrIdx, 5), " ", "")
Dim ListItems() As String
ListItems = Split(CurrList, ",")
Dim ListIdx As Integer
For ListIdx = LBound(ListItems) To UBound(ListItems)
Range("A" & CStr(FirstRow + RowCount)).Value = CurrCat
Range("E" & CStr(FirstRow + RowCount)).Value = ListItems(ListIdx)
RowCount = RowCount + 1
Next ListIdx
Next ArrIdx
End Sub
以下是我得到的结果:
<- A -> <- B> < -C-> <- D-> <- E >
1 Cat1 date1 a x,y,z a
2 Cat1 date2 b r,s b
3 Cat1 date3 c p,q c
4 Cat2 date4 d x,y e
5 Cat2 f
6 Cat3 g
7 Cat3 h
8 Cat4 i
9 Cat4 j
只有A和E列正在扩展而其他列则没有扩展。
以下是预期结果:
<- A -> <- B> < -C-> <- D-> <- E >
1 Cat1 date1 a x a
2 Cat1 date1 a y b
3 Cat1 date1 a z c
4 Cat2 date2 b r e
5 Cat2 date2 b s f
6 Cat3 date3 c p g
7 Cat3 date3 c q h
8 Cat4 date4 d x i
9 Cat4 date4 d y j