Hello. I have this code already that I found on this site and edited it a little bit to my fit my needs. I have two different workbooks. They each have most of the same headers but the order of them can be changed at random times unfortunately.
So I need to copy and paste all the data from my origin workbook’s “Combined” sheet matching the column headers to “Sheet1” in the Audit.csv workbook. This code does this somewhat however, I need it to start pasting the data down bottom after the last row used (aka first empty row). I will always have data in “Sheet”1 as this is a master data sheet I am building. Currently it starts pasting from the top of the worksheet. Also for some reason it pastes over some of my data midway through. Here is a screenshot showing an example of what both worksheets look like and here is the code. Thank you to anyone willing to help.
So I need to copy and paste all the data from my origin workbook’s “Combined” sheet matching the column headers to “Sheet1” in the Audit.csv workbook. This code does this somewhat however, I need it to start pasting the data down bottom after the last row used (aka first empty row). I will always have data in “Sheet”1 as this is a master data sheet I am building. Currently it starts pasting from the top of the worksheet. Also for some reason it pastes over some of my data midway through. Here is a screenshot showing an example of what both worksheets look like and here is the code. Thank you to anyone willing to help.
VBA Code:
Sub CopyPasteBasedonHeaders()
Dim sh1 As Worksheet, sh2 As Worksheet, wb1 As Workbook, wb2 As Workbook, a() As Variant, b() As Variant
Dim i As Long, j As Long, lr As Long, lc As Long, lr2 As Long
Set wb1 = ThisWorkbook
Set wb2 = Workbooks.Open("C:\Users\" & Environ("username") & "\Documents\Audit.csv")
Set sh1 = wb2.Sheets("Combined") 'origin
Set sh2 = wb1.Sheets("Sheet1") 'destination
'last row on origin sheet
lr = sh1.Range("A" & Rows.Count).End(xlUp).Row
'last row on destination sheet
lr2 = sh2.Range("A" & Rows.Count).End(xlUp).Row + 1
'Store headers in the "a" variable of the origin sheet
lc = sh1.Cells(1, Columns.Count).End(xlToLeft).Column
a = WorksheetFunction.Transpose(sh1.Range("A1", sh1.Cells(1, lc)).Value)
'Store headers in the "b" variable of the destination sheet
lc = sh2.Cells(1, Columns.Count).End(xlToLeft).Column
b = WorksheetFunction.Transpose(sh2.Range("A1", sh2.Cells(1, lc)).Value)
For i = 1 To UBound(a, 1)
For j = 1 To UBound(b, 1)
'Compare header
If b(j, 1) = a(i, 1) Then
'copy the column
sh2.Cells(2, j).Resize(lr).Value = sh1.Cells(2, i).Resize(lr).Value
Exit For
End If
Next
Next
MsgBox "End"
End Sub