如何将具有多个属性的列拆分为多个列?

时间:2015-01-24 18:51:20

标签: excel excel-formula

我有一个excel文件,其中包含两列活动&的结果

活动是一个字符串列,其中包含三个可能的值,例如abc

结果列包含表单提交中的值,所有这些值都按如下方式组合在一起:

Result
option1: 2; option2: 4; option3: 2

所有行的选项都不相同。选项取决于活动列中的值。因此,示例文件看起来像

Activity,Result
a       , "a1: 1; a2: 4; a3: 5"
a       , "a1: 3; a2: 1; a3: 5"
a       , "a1: 4; a2: 3; a3: 5"
b       , "b1: 2; b2: 4; b3: 2"
b       , "b1: 3; b2: 4; b3: 2"
b       , "b1: 1; b2: 3; b3: 1"

我想将此文件转换为包含选项的格式,如下所示

Activity, a1, a2, a3, b1, b2, b3
a       ,  1,  4,  5,   ,   ,   
a       ,  3,  1,  5,   ,   ,    
b       ,   ,   ,   ,  2,  4,  3

有没有办法在Excel中执行此操作?另外,我不介意为每个选项(a,b和c)创建单独的文件。

1 个答案:

答案 0 :(得分:0)

如图1所示放置数据,创建工作表2并将其留空,以下代码将给出您已概述的输出...

ActiveWorkbook.Sheets(2).Cells.ClearContents
ActiveWorkbook.Sheets(2).Cells(1, 1).Value = "Activity"
ActiveWorkbook.Sheets(2).Cells(1, 2).Value = "a1"
ActiveWorkbook.Sheets(2).Cells(1, 3).Value = "a2"
ActiveWorkbook.Sheets(2).Cells(1, 4).Value = "a3"
ActiveWorkbook.Sheets(2).Cells(1, 5).Value = "b1"
ActiveWorkbook.Sheets(2).Cells(1, 6).Value = "b2"
ActiveWorkbook.Sheets(2).Cells(1, 7).Value = "b3"

Dim c() As String
c = Split("a1,a2,a3,b1,b2,b3", ",")

Dim firstActivity, lastActivity, t1, t2 As Integer
firstActivity = 2
lastActivity = ActiveWorkbook.Sheets(1).Cells(Rows.Count, 1).End(xlUp).Row

Dim Result As String

For i = 2 To lastActivity
    Result = ActiveWorkbook.Sheets(1).Cells(i, 2).Value
    ActiveWorkbook.Sheets(2).Cells(i, 1).Value = ActiveWorkbook.Sheets(1).Cells(i, 1).Value
    For i2 = 0 To 5
        t1 = InStr(1, Result, c(i2), 1)
        If (t1 = 0) Then GoTo skip
        t1 = InStr(t1, Result, " ", 1)
        t2 = InStr(t1, Result, ";", 1)
           If (t2 = 0) Then
             t2 = InStr(t1, Result, """", 1)
           End If
        ActiveWorkbook.Sheets(2).Cells(i, i2 + 2).Value = Mid(Result, t1, t2 - t1)
skip:
    Next i2
    Next i

输入(第1页)

Activity    ,Result
a   , "a1: 1; a2: 4; a3: 5"
a   , "a1: 3; a2: 1; a3: 5"
a   , "a1: 4; a2: 3; a3: 5"
b   , "b1: 2; b2: 4; b3: 2"
b   , "b1: 3; b2: 4; b3: 2"
b   , "b1: 1; b2: 3; b3: 1"

输出(第2页)

Activity    a1  a2  a3  b1  b2  b3
a   1   4   5           
a   3   1   5           
a   4   3   5           
b               2   4   2
b               3   4   2
b               1   3   1

不要介意他们完美排列的列,但是当我将其粘贴到此处时,网站格式会搞砸了。你甚至可以用公式而不是VBA来完成这个,但是我上面写的宏完全实现了你所概述的内容,如果有你忘记提及的详细信息并希望我修改代码请告诉我。当然,最好的解决方案是尽可能停止以这种方式输入数据。