Monday, April 16, 2012

Move data from Row to Column

When there is a huge data in a single column; we may need to migrate some data to next column using page break. VBA code for this utility:

Option Explicit
Dim sht As Worksheet, myrng As Range, myrng1 As Range, count As Integer, i As Long
Dim myrng2 As Range, rowcount As Long
Sub moveRowtoColumn()
On Error Resume Next
Set sht = ThisWorkbook.Sheets(1)
Set myrng = sht.UsedRange.Columns(1)
count = sht.HPageBreaks.count
i = 0

For i = 1 To count
 
    Set myrng1 = sht.HPageBreaks(i).Location
    Set myrng2 = sht.HPageBreaks(i + 1).Location.Offset(-1, 0)
        If myrng2 Is Nothing Then
            Range(myrng1, myrng.Cells(65500, 1).End(xlUp)).Copy Destination:=sht.Cells(1, i + 1)
        Else
            Range(myrng1, myrng2).Copy Destination:=sht.Cells(1, i + 1)
        End If
     
    Set myrng1 = Nothing
    Set myrng2 = Nothing
Next

sht.Range(sht.HPageBreaks(1).Location.Address, myrng.Cells(65500, 1).End(xlUp).Address).Delete
    Set myrng = Nothing
End Sub

No comments:

Post a Comment