Use this code -
Option Explicit
Dim WeeklyFN As String
Dim MainFN As String
Dim MFile As String
Dim lrow As Long
Dim sfield As String
Dim cellcol As Long
Dim i As Long
Dim lastrow As Long
Dim c As Object
Sub find_cols()
MFile = ActiveWorkbook.Name
Application.ScreenUpdating = False
proceed:
WeeklyFN = Application.GetOpenFilename(FileFilter:="All files (*.*), *.*", Title:="Please open the Weekly file")
If WeeklyFN = "" Then
MsgBox "You have not selected a file."
GoTo proceed
Else
Workbooks.Open Filename:=WeeklyFN
WeeklyFN = ActiveWorkbook.Name
End If
proceed1:
MainFN = Application.GetOpenFilename(FileFilter:="All files (*.*), *.*", Title:="Please open the Main file")
If MainFN = "" Then
MsgBox "You have not selected a file."
GoTo proceed1
Else
Workbooks.Open Filename:=MainFN
MainFN = ActiveWorkbook.Name
End If
Workbooks(MFile).Worksheets("Sheet1").Columns("A:A").Delete
Workbooks(WeeklyFN).Worksheets("Sheet1").Rows("1:1").Copy
Workbooks(MFile).Worksheets("Sheet1").Range("A1").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=True
Application.CutCopyMode = False
lrow = Workbooks(MFile).Worksheets("Sheet1").Range("A" & Rows.Count).End(xlUp).Row
For i = 1 To lrow
sfield = Workbooks(MFile).Worksheets("Sheet1").Range("A" & i).Value
Workbooks(MainFN).Worksheets("Sheet1").Range("A2").Select
On Error Resume Next
Workbooks(MainFN).Worksheets("Sheet1").Rows("1:1").Find(What:=sfield, After:=Range("A1"), LookIn:=xlValues, Lookat:=xlPart, SearchOrder:=xlByRows, _
SearchDirection:=xlNext, MatchCase:=False, searchformat:=False).Activate
On Error GoTo 0
cellcol = ActiveCell.Column
lastrow = Workbooks(WeeklyFN).Worksheets("Sheet1").Range("A" & Rows.Count).End(xlUp).Row
With Workbooks(WeeklyFN).Worksheets("Sheet1")
.Range(.Cells(2, i), .Cells(lastrow, i)).Copy Workbooks(MainFN).Worksheets("Sheet1").Cells(2, cellcol)
End With
Application.CutCopyMode = False
Next i
End Sub
Just for your information - i didnt find the "Branch" field in the Excel Spreadsheet. There could be a few more like that but the code ignores them. Try this code and let me know if the fields have been copied properly. You are the best judge of that.
Bookmarks