Excel宏 - 逗号分隔单元格到不同工作表的行

时间:2016-07-14 09:40:19

标签: excel vba excel-vba

我的Excel中有两张纸。在我的Excel中拥有以下数据 在第一张纸上,我有

 column 1: a     Column 2: p,q,r,s      Column 3: u,v,w      Column 4: x,y,z
 column 1: b     Column 2: q,r          Column 3: u,v,w      Column 4:  z 

.......等##

每行,代表一行和一个单元格。

我想将其转换为:

 1. (column 1) a   (column 2) p 
 2. (column 1) a   (column 2) q   
 3. (column 1) a   (column 2) r 
 4. (column 1) a   (column 2) s 
 5. (column 1) a                      (column 3) u 
 6. (column 1) a                      (column 3) v 
 7. (column 1) a                      (column 3) w 
 8. (column 1) a                                          (column 4) x 
 9. (column 1) a                                          (column 4) y 
 10.(column 1) a                                          (column 4) z

1 个答案:

答案 0 :(得分:0)

尝试使用以下代码

Sub test()
    Dim lastrow, lastcolumn, i, j, k As Long
    Dim str1, str2
    lastrow = Range("A" & Rows.Count).End(xlUp).Row
    lastcolumn = Cells(1, Columns.Count).End(xlToLeft).Column
    For i = 1 To lastrow
        For j = 2 To lastcolumn
            str1 = Split(Cells(i, j), ",")
            str2 = UBound(str1)
            For k = 0 To str2
                With Sheets("Sheet2")
                    .Range("A" & .Range("A" & Rows.Count).End(xlUp).Row + 1).Value = Cells(i, 1)
                    .Range("B" & .Range("B" & Rows.Count).End(xlUp).Row + 1).Value = str1(k)
                End With
            Next k
        Next j
    Next i
End Sub

工作证明

enter image description here