The reason I set the second copy destination to the "F" column was because thats where i thought the "AB" column from worksheet A needed to go. I could have been entirely wrong. In answer to your question about searching for string names, while it sounds easy on paper, coding a macro to do it is something else. Hered what it would look like
Option Explicit
Sub CopyData2()
Dim lastcol As Long, lastrow As Long
Dim icol As Variant, bcol As Variant
'counts how many columns there are
lastcol = Sheets("Worksheet A").Cells(1, Columns.Count).End(xlToLeft).Column
'counts how many rows there are
lastrow = Sheets("Worksheet A").Range("A" & Rows.Count).End(xlUp).Row
'loop
For Each icol In Sheets("Worksheet A").Range("1:1")
'the word in ""'s is what you are comparing against
If InStr(1, icol, "supplier", vbTextCompare) Then
icol.EntireColumn.Copy
End If
For Each bcol In Sheets("Worksheet B").Range("1:1")
If InStr(1, icol, "id", vbTextCompare) Then
bcol.PasteSpecial xlPasteAll
GoTo Last
End If
Next bcol
'For Each bcol In Sheets("Worksheet B").Range("1:1")
' If bcol.Value = "id" Then
' bcol.PasteSpecial xlPasteAll
' GoTo Last
' End If
' Next bcol
Next icol
Last:
End Sub
I tested it out on the sheet and it work. I would like to point out that where you see an apostraphy it means that the code will not read that part. So essentially I can write messages that only someone looking at the code will see. The macro will go right over it without looking at it. I have included, even though it probably isnt neccessary or even best, a string search function. Basically you can have it search row 1 for whatever "like" word you want. So in this situation it will find anything that has "supplier" in it, like for example "supplier_id". If you know exactly what the cell value is going to be it would be best just to say icol.value = "whatever". I put a snippet of code in to show you what that would look like.
Note: This is not the most efficient way to do this. For some reason i can do things great going down rows but going left to right on columns seems to screw me up. This is my own failing and I am working hard to fix it. Nonetheless it works. Maybe a more advanced member can update to a more efficient code. Let me know.
Bookmarks