Hi,
I have this code that will copy/paste multiple columns between two spreadsheets, basically an "import". The issue is that the "Import" sheet will always be changing with more or less columns than the "Main" worksheet (which is the template).
The code below just copy/pastes all columns. I need a way to match the headers text and paste all the related data from "Import" sheet to "Main".
Here is my code, any help would be appreciated:
Sub CopyByHeader()
Dim shtImport As Worksheet
Dim shtMain As Worksheet
Set shtImport = ActiveSheet ' "import" - could be different workbook
Set shtMain = ThisWorkbook.Sheets("Main")
Dim lCopyColumn As Long
Dim lCopyRow As Long
Dim lLastRowOfColumn As Long '- for each column in row 1 of import sheet
For lCopyColumn = 1 To shtImport.Cells(1, shtImport.Columns.Count).End(xlToLeft).Column
'- check what the last row is with data in column
lLastRowOfColumn = shtImport.Cells(shtImport.Rows.Count, lCopyColumn).End(xlUp).Row
'if last row was larger than one then we will loop through rows and copy
If lLastRowOfColumn > 1 Then
For lCopyRow = 1 To lLastRowOfColumn
'- copying to the corresponding cell address, this can be modified.
shtMain.Cells(lCopyRow + 6, lCopyColumn).Value = shtImport.Cells(lCopyRow, lCopyColumn).Value
Next lCopyRow
End If
Next lCopyColumn
End Sub
Thanks!
I have this code that will copy/paste multiple columns between two spreadsheets, basically an "import". The issue is that the "Import" sheet will always be changing with more or less columns than the "Main" worksheet (which is the template).
The code below just copy/pastes all columns. I need a way to match the headers text and paste all the related data from "Import" sheet to "Main".
Here is my code, any help would be appreciated:
Sub CopyByHeader()
Dim shtImport As Worksheet
Dim shtMain As Worksheet
Set shtImport = ActiveSheet ' "import" - could be different workbook
Set shtMain = ThisWorkbook.Sheets("Main")
Dim lCopyColumn As Long
Dim lCopyRow As Long
Dim lLastRowOfColumn As Long '- for each column in row 1 of import sheet
For lCopyColumn = 1 To shtImport.Cells(1, shtImport.Columns.Count).End(xlToLeft).Column
'- check what the last row is with data in column
lLastRowOfColumn = shtImport.Cells(shtImport.Rows.Count, lCopyColumn).End(xlUp).Row
'if last row was larger than one then we will loop through rows and copy
If lLastRowOfColumn > 1 Then
For lCopyRow = 1 To lLastRowOfColumn
'- copying to the corresponding cell address, this can be modified.
shtMain.Cells(lCopyRow + 6, lCopyColumn).Value = shtImport.Cells(lCopyRow, lCopyColumn).Value
Next lCopyRow
End If
Next lCopyColumn
End Sub
Thanks!