有一个excel问题,我们有一个列的值如下所示,我们希望各个值进入相应的新列,如分配,主要目的等。
数据就像
Allocation: Randomized|Endpoint Classification: Safety/Efficacy Study|Intervention Model: Parallel Assignment|Masking: Double Blind (Subject, Caregiver)|Primary Purpose: Treatment
Allocation: Randomized|Primary Purpose: Treatment
Allocation: Randomized|Intervention Model: Parallel Assignment|Masking: Open Label|Primary Purpose: Treatment
有很多像这样的行。
答案 0 :(得分:2)
首先使用text to columns
使用|
分隔符来分割数据。
在A6
中添加以下内容并根据需要向下/向下拖动:
=IFERROR(MID(INDEX(1:1,0,(MATCH("*"&A$5&"*",1:1,0))),FIND(":",INDEX(1:1,0,(MATCH("*"&A$5&"*",1:1,0))),1)+2,1000),"")
它使用MATCH
/ INDEX
函数来获取包含标题的单元格的文本,然后使用MID
/ FIND
函数获取:
之后的文本1}}。然后将整个公式括在IFERROR
中,这样如果某些行不包含特定的标题项,则返回空白而不是#N/A
的
答案 1 :(得分:1)
你没有要求VBA解决方案,但无论如何这里都是。
在下面的代码中,您可能需要重命名源数据所在的工作表。如果结果工作表尚不存在,将添加结果工作表 - 随意重命名。
首先在您的数据副本上进行测试,以防万一。
请务必按照代码中的说明设置对 Microsoft Scripting Runtime (工具 - >参考)的引用。
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
如果您之前没有使用过宏,要输入此宏(Sub), alt-F11 将打开Visual Basic编辑器。 确保在Project Explorer窗口中突出显示您的项目。 然后,从顶部菜单中选择“插入/模块” 将下面的代码粘贴到打开的窗口中。
要使用此宏(子),请打开宏对话框。按名称选择宏,然后 RUN 。