I am looking for a macro to copy data matching column headers between two OPEN workbooks. I have below code to copy data between sheets in the same workbook. But I need as below to copy between TWO OPEN workbooks.
- First open the Destination Workbook (Have a macro button in it to copy data)
- Second open source workbook (to physically see and verify data)
- Third, go to destination workbook and click button to copy.
Can anyone please help me.
Sub CopyMatchingHeaders()
Dim wbSource As Workbook
Dim SFileName As Variant
SFileName = Application.GetOpenFilename("Excel Files, *.xlsx, *.xls*,", MultiSelect:=False)
If TypeName(SFileName) = "String" Then
Set wbSource = Workbooks.Open(SFileName)
Else
MsgBox "No file selected."
Exit Sub
End If
Dim header As Range, headers As Range
Set headers = ActiveWorkbook.Worksheets("Sheet1").Range("A1:AE1")
For Each header In headers
If GetHeaderColumn(header.Value) > 0 Then
Range(header.Offset(1, 0), header.End(xlDown)).Copy Destination:=ActiveWorkbook.Worksheets("Sheet2").Cells(2, GetHeaderColumn(header.Value))
End If
Next
End Sub
Function GetHeaderColumn(header As String) As Integer
Dim headers As Range
Set headers = ActiveWorkbook.Worksheets("Sheet2").Range("A1:AE1")
GetHeaderColumn = IIf(IsNumeric(Application.Match(header, headers, 0)), Application.Match(header, headers, 0), 0)
End Function