我有一个CSV文件,其中包含以下列之一的键:值数据:
id|name|age|data
1|steve|5 |a:5,b:1,e:7
2|john |10|c:3,b:2,e:4
3|jack |12|e:4,c:2,d:7,b:9
我想将其全部拆分如下:
id|name |age|a|b|c|d|e
1 |steve|5 |5|1| | |7
2 |john |10 | |2|3| |4
3 |jack |12 | |9|2|7|4
答案 0 :(得分:1)
这应该足以让你入门。
Sub split_and_sort()
Dim rw As Long, v As Long, vKEYs As Variant, vPAIR As Variant
With Worksheets("Sheet5") '<~~ set this wroksheet reference properly!
With .Cells(1, 1).CurrentRegion
.Cells(1, .Columns.Count).Resize(1, 5) = Array("a", "b", "c", "d", "e")
With .Resize(.Rows.Count, .Columns.Count + 4)
For rw = 2 To .Rows.Count
vKEYs = Split(.Cells(rw, 4).Value2, Chr(44))
.Cells(rw, 4).Clear
For v = LBound(vKEYs) To UBound(vKEYs)
vPAIR = Split(vKEYs(v), Chr(58))
If CBool(UBound(vPAIR)) Then
If IsError(Application.Match(vPAIR(0), .Rows(1), 0)) Then _
.Cells(1, Columns.Count).End(xlToLeft).Offset(0, 1) = vPAIR(0)
.Cells(rw, Application.Match(vPAIR(0), .Rows(1), 0)) = vPAIR(1)
End If
Next v
Next rw
End With
End With
End With
End Sub
如果D列中的单元格没有值或流氓值,这些值不会先在逗号上分割,然后再在冒号上分割,则可能需要添加一些错误控制