您沒有要求提供VBA解決方案,但無論如何都是這樣。
- 通過檢查每個行確定列標題,產生頭的唯一列表,將其存儲在一個字典
- 您可以添加一個程序來進行排序或命令頭
- 創建一個「結果」陣列並將標題寫入第一行,使用字典存儲列號以供稍後查找
- 再次檢查每一行並提取與每個列標題關聯的值,在結果數組中填充正確的插槽。
- 將結果數組寫入「結果」工作表。
在下面的代碼中,您可能需要重命名源數據所在的工作表。結果工作表將被添加,如果它尚不存在 - 隨時重命名它。
先測試一下你的數據,以防萬一。
請確保將參考設置爲Microsoft腳本運行時(工具 - >參考),如代碼註釋中所示。
Option Explicit
'Set References
' Microsoft Scripting Runtime
Sub MakeColumns()
Dim vSrc As Variant, vRes As Variant
Dim wsSrc As Worksheet, wsRes As Worksheet, rRes As Range
Dim dHdrs As Dictionary
Dim V As Variant, W As Variant
Dim I As Long, J As Long
Set wsSrc = Worksheets("Sheet1")
'Get source data
With wsSrc
vSrc = .Range(.Cells(1, 1), .Cells(.Rows.Count, 1).End(xlUp))
End With
'Set results sheet and range
On Error Resume Next
Set wsRes = Worksheets("Results")
If Err.Number = 9 Then
Worksheets.Add.Name = "Results"
End If
On Error GoTo 0
Set wsRes = Worksheets("Results")
Set rRes = wsRes.Cells(1, 1)
'Get list of headers
Set dHdrs = New Dictionary
dHdrs.CompareMode = TextCompare
'Split each line on "|" and then ":" to get header/value pairs
For I = 1 To UBound(vSrc, 1)
V = Split(vSrc(I, 1), "|")
For J = 0 To UBound(V)
W = Split(V(J), ":") 'W(0) will be header
If Not dHdrs.Exists(W(0)) Then _
dHdrs.Add W(0), W(0)
Next J
Next I
'Create results array
ReDim vRes(0 To UBound(vSrc, 1), 1 To dHdrs.Count)
'Populate Headers and determine column number for lookup when populating
'Could sort or order first if desired
J = 0
For Each V In dHdrs
J = J + 1
vRes(0, J) = V
dHdrs(V) = J 'column number
Next V
'Populate the data
For I = 1 To UBound(vSrc, 1)
V = Split(vSrc(I, 1), "|")
For J = 0 To UBound(V)
'W(0) is the header
'The dictionary will have the column number
'W(1) is the value
W = Split(V(J), ":")
vRes(I, dHdrs(W(0))) = W(1)
Next J
Next I
'Write the results
Set rRes = rRes.Resize(UBound(vRes, 1) + 1, UBound(vRes, 2))
With rRes
.EntireColumn.Clear
.Value = vRes
With .Rows(1)
.Font.Bold = True
.HorizontalAlignment = xlCenter
End With
.EntireColumn.AutoFit
End With
End Sub
如果你以前沒有使用宏,進入這個宏(子),ALT-F11打開Visual Basic編輯器。 確保您的項目在Project Explorer窗口中突出顯示。 然後,從頂部菜單中選擇插入/模塊,然後將下面的代碼粘貼到打開的窗口中。
要使用此宏(子),打開宏對話框。按名稱選擇宏,並且RUN。
使用[文本到列](https://support.office.com/en-gb/article/Split-text-into-different-columns-with-the-Convert-Text-to-Columns-Wizard- 30b14928-5550-41f5-97ca-7a3e9c363ed7) – Jordan