Transpose a single column to multiple rows

后端 未结 2 1829
有刺的猬
有刺的猬 2021-01-29 08:58

I have one column of data with approximately 800 records. Each 18 cells is one record. I need a script that takes every 18 cells and transposes them to a row dynamically, or ev

相关标签:
2条回答
  • 2021-01-29 09:29

    you can use this VBA code to achieve this .

        Public Sub TransposePaste()
       'Value we want to step by....
        Dim stepVal As Long
        stepVal = 18
    'Declare start row variable (-1)
     Dim row As Long
     row = 0
    
    'Declare the column the data is coming from
    Dim col As Long
    col = 1
    
    'Declare and set worksheet
    Dim ws As Worksheet
    Set ws = Sheet1
    
    'end row of the data
    Dim endRow As Long
    
    
    endRow = ws.Cells(ws.Rows.Count, col).End(xlUp).row
    
    'cycle to end of data end of data...
    For i = 1 To endRow Step stepVal
    
    'increment row each time
    row = row + 1
    
        'cycle through the columns outputting the data
        For j = 1 To stepVal
    
        Sheet1.Cells(row, j).Value = Sheet1.Cells(i + j - 1, col).Value
    
        Next j
    Next i
    

    End Sub

    0 讨论(0)
  • 2021-01-29 09:30

    You'll probably get asked "what have you tried" since it's preferred that you have a bash at it and ask when you get stuck rather than asking for a complete solution. That having been said, I can offer you some tips to get you started.

    To do this in VBA you need to perform a loop which starts at the first cell, gets a range consisting of that cell and the following 18 rows, then pastes that into (probably) another sheet in the workbook, transposing it from a column to a row. The loop will then offset 19 cells and start again.

    Take a look at the answer that I gave in this thread: Unable to write a Macro for Excel VBA to copy a specific cell value to the next blank rows

    That will give you the syntax for doing a loop which is somewhat similar to yours.

    To get the syntax for doing a paste / transpose, do it manually and record your actions using the macro recorder. That can be found on the Developer tab. (If you don't have the Developer tab visible, go to File -> Options -> Customise Ribbon and turn on the Developer tab there.)

    Give it a try, and if you find that you can't quite make it work just post again with the details of where you're getting stuck.

    0 讨论(0)
提交回复
热议问题