Split single row into multiple rows based on cell value in excel

天大地大妈咪最大 提交于 2019-12-01 01:41:52

This should do your job. Considering your data to be in Sheet1 and output is generated in Worksheet Sheet2.

 Sub pSplitData()

        Dim rngColLoop          As Range
        Dim rngSheet1           As Range
        Dim wksSheet2           As Worksheet
        Dim intColCounter       As Integer
        Dim intRowCounter       As Integer

        'Consider the data to be in First row of Sheet1
        With Worksheets("Sheet1")
            Set rngSheet1 = .Range(.Range("A1"), .Range("A1").End(xlToRight))
        End With

        Set wksSheet2 = Worksheets("Sheet2")
        intRowCounter = 1
        intColCounter = 0

        'Clear previous output
        wksSheet2.Range("A1").CurrentRegion.Clear

        'Loop through and create output in Sheet2
        With rngSheet1
            For Each rngColLoop In .Columns
                If Trim(rngColLoop) <> "" Then
                    If UCase(Trim(rngColLoop)) <> "A" Then
                        intColCounter = intColCounter + 1
                        wksSheet2.Cells(intRowCounter, intColCounter) = rngColLoop
                    ElseIf UCase(Trim(rngColLoop)) = "A" Then
                        intRowCounter = intRowCounter + 1
                        intColCounter = 1
                        wksSheet2.Cells(intRowCounter, intColCounter) = rngColLoop
                    End If
                End If
            Next rngColLoop
        End With

        Set rngColLoop = Nothing
        Set rngSheet1 = Nothing
        Set wksSheet2 = Nothing

End Sub

Try using Text to Columns and use A as your delimiter. You'll have to add the A back into the resulting cells.

If your data is in a single cell, say, cell A1, then you can use vba's split to store all of the individual pieces in an array, split with the letter A.

myArray = Split(Cells(1, 1), "A")

In your example, myArray(0) = 1 2 3 4 5, myArray(1) = 1 2 4 9 5, etc.

So if each of those elements needs to be in its own row, you can concatenate the A back onto the front, like so

cells(2, 1) = "A" & myArray(0)
cells(3, 1) = "A" & myArray(1)

and so forth.

if your data is like this:

      A    ||  B   ||  C     ||  D   ||
-----------------------------------------
1 ||  one  || two  || three  || four ||
2 ||

then put =TRANSPOSE(A1:D1) in A2, and confirm with Ctrl+shift+enter, which will result in formula that looks like: {=TRANSPOSE(A1:D1)}

and a result that looks like:

      A    ||  B   ||  C     ||  D   ||
-----------------------------------------
1 ||  one  || two  || three  || four ||
2 ||  one
3 ||  two
4 ||  three
5 ||  four

or you you are after a one-off operation you can always: select -> copy ; select empty cell -> paste special -> tick transpose

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!