I have written the following code which should, match column headings in destination workbook, search for the same column heading in the source workbook (worksheet), fetch all the data under that particular column till the end of the row and copy it under the same column heading in the destination workbook (worksheet).
This task should be performed till all the columns in the destination workbook's worksheet gets filled.
Sub LPN()
Dim CurrentWS As Worksheet
Set CurrentWS = ActiveSheet
ActiveWorkbook.Sheets("controls").Select
'I have made a sheet in the main workbook(Rates EMEA CDS PT+FVA.v1.25 Apr 2016.i1.xlsm)
' known as **controls** , in this sheet I have specified the path of the
' workbook(worksheet) that has to be opened and from where the data has to be copied.
'The name of the cell where the path has been mentioned I named it as GPL
Set master = ActiveWorkbook
GPL = Range("GPL").Value
Workbooks.Open Filename:=GPL
Set GPLfile = ActiveWorkbook
'Open the particular workbook with specified worksheet having .xlsx extension
Dim SourceWS As Worksheet
Set SourceWS = ActiveWorkbook.Worksheets("PNL Attribution")
Dim SourceHeaderRow As Integer: SourceHeaderRow = 1
Dim SourceCell As Range
Workbooks("Rates EMEA CDS PT+FVA.v1.25 Apr 2016.i1.xlsm").Activate
Dim TargetWS As Worksheet
Set TargetWS = Worksheets("PNL Attribution")
Dim TargetHeader As Range
'The code will look for all the column headings in the source workbook
' match it with the headings in the target workbook(worksheet) which are not in order.
Set TargetHeader = TargetWS.Range("A10:ZZ10")
Dim RealLastRow As Long
Dim SourceCol As Integer
SourceWS.Activate
For Each Cell In TargetHeader
If Cell.Value <> "" Then
Set SourceCell = Rows(SourceHeaderRow).Find _
(Cell.Value, LookIn:=xlValues, LookAt:=xlWhole)
If Not SourceCell Is Nothing Then
SourceCol = SourceCell.Column
RealLastRow = Columns(SourceCol).Find("*", LookIn:=xlValues, _
SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
If RealLastRow > SourceHeaderRow Then
Range(Cells(SourceHeaderRow + 1, SourceCol), Cells(RealLastRow, _
SourceCol)).copy
TargetWS.Cells(2, Cell.Column).PasteSpecial xlPasteValues
End If
End If
End If
Next
CurrentWS.Activate
End Sub
TargetHeader
range). finally ... watch what happens and if it isn't satisfactory step through the code placing breakpoints in it where you may find appropriate and press F8 to see what's happening (query variable values in the Immediate Window"). Trial & error is what we all have been through and learned the most from. – user3598756