0

I have two sheets in my Workbook. Both have same columns but in different order. I need to copy all the rows from one sheet to another.

Any way to copy the data exactly under matching column names ? Both sheets have columns upto CZ.

1 Answer 1

1

You'll need to do VB Editor Menu/Tools/References and check the box next to Microsoft Scripting Runtime. That gives you access to Scripting.Dictionary, which is a keyed hash object (key/value pairs)

Sub CopyByCol()

Dim lCol As Long, lCols As Long, sCol As String, lRows As Long
Dim dictCol As New Scripting.Dictionary
Dim rFrom As Range, rTo As Range

    Set rFrom = Sheet1.Range("A1")
    Set rTo = Sheet2.Range("A1")

' Store hash of where column names occur in target sheet, keyed by Col name
    lCols = rFrom.Offset(0, 255).End(xlToLeft).Column - rFrom.Column
    For lCol = 0 To lCols
        sCol = rTo.Offset(0, lCol).Value
        dictCol.Add sCol, lCol
    Next

' Get key column name from From sheet, and write to correct col in To sheet
    For lCol = 0 To lCols
        sCol = rFrom.Offset(0, lCol).Value
        lRows = rFrom.Offset(65000, lCol).End(xlUp).Row - rFrom.Row
        Range(rFrom.Offset(1, lCol), rFrom.Offset(lRows, lCol)).Copy Destination:=rTo.Offset(1, dictCol(sCol))
    Next

End Sub
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.