目前,我有這個數據在片拆分逗號分隔的條目將新行
Col A Col B
1 angry birds, gaming
2 nirvana,rock,band
我想要做的第二列拆分逗號分隔的條目,並在新行添加如下內容:
Col A Col B
1 angry birds
1 gaming
2 nirvana
2 rock
2 band
我相信這可以使用VBA完成,但無法自己弄清楚。
目前,我有這個數據在片拆分逗號分隔的條目將新行
Col A Col B
1 angry birds, gaming
2 nirvana,rock,band
我想要做的第二列拆分逗號分隔的條目,並在新行添加如下內容:
Col A Col B
1 angry birds
1 gaming
2 nirvana
2 rock
2 band
我相信這可以使用VBA完成,但無法自己弄清楚。
您最好使用變長數組,而不是電池的循環 - 它們快得多代碼明智的,一旦數據集是有意義的。即使你的代碼更長:)
下面的示例轉儲到C和D列,以便您可以看到原始數據。 更改[c1].Resize(lngCnt, 2).Value2 = Application.Transpose(Y)
到[a1].Resize(lngCnt, 2).Value2 = Application.Transpose(Y)
傾倒在自己的原始數據
[用正則表達式,
即後刪除任何空白更新 「帶」 變成 「帶」]
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
注意到你的數據在A列,並把結果列C.
Sub SplitAll()
Dim src As Range
Dim result As Variant
For Each src In Range("A:A").SpecialCells(xlCellTypeConstants)
result = Split(src, ",")
'last cell in column C
With Cells(Rows.Count, 3).End(xlUp)
Range(.Offset(1, 0), .Offset(1 + UBound(result, 1), 0)) = Application.WorksheetFunction.Transpose(result)
End With
Next src
End Sub
Ooops,我剛剛看到Kannan S.提供的鏈接。看起來我沒有工作。無論如何,我的代碼更短:-)) – 2011-12-19 12:27:11
是的 - 你的代碼只拆分列A .....但要處理的數據是列B(以A作爲標記)它的兩列輸出。 :) – brettdj 2011-12-19 12:38:22
至少,這將是一個不錯的redGREENblue小型練習;-) – 2011-12-19 12:56:13
你試圖就地做到這一點,或者你使用新工作表很好嗎? – 2011-12-19 11:38:36
這是很好的任何方式。 – redGREENblue 2011-12-19 11:39:55
你到目前爲止嘗試過嗎?什麼工作?什麼沒有? – 2011-12-19 11:42:02