VBA Code for copying and pasting data from one sheet to another based on column headers

Shree1

New Member
Joined
Sep 8, 2014
Messages
31
On sheet 1,in workbook1 cells A1:E1 have column headings, but no data. On sheet 1 of workbook2, the data range is A1: AC5000. I want to pick out the columns in this worksbook that match the headers on workbook1, copy and paste them under the column headers in workbook1. Can someone help me with this please
.
I found the below code
im header As Range, headers As Range
Set headers = wsCopyFrom1.Range("A1:AR1")
For Each header In headers
If GetHeaderColumn(header.Value) > 0 Then
Range(header.Offset(1, 0), header.End(xlDown)).Copy Destination:=wsCopyTo1a.Cells(2, GetHeaderColumn(header.Value))
End If
Next
End Sub
Function GetHeaderColumn(header As String) As Integer
Dim headers As Range
Set headers = wsCopyTo1a.Range("A1:E1")
GetHeaderColumn = IIf(IsNumeric(Application.Match(header, headers, 0)), Application.Match(header, headers, 0), 0)
End Function


But I am getting an error 404 message )object not defined) at Set hedares=wsCopyTo1a.Range.. bit.
I have set wsCopyto1a as a worksheet etc.
Please help!
 

Excel Facts

What is the shortcut key for Format Selection?
Ctrl+1 (the number one) will open the Format dialog for whatever is selected.
The below worked.
Dim c As Range
Dim Rng As Range
Dim i As Integer
Dim r As Range, Cell As Object
With wsCopyFrom1.Range("a1").CurrentRegion
For Each r In wsCopyTo1a.Range("a1:g1")
Set c = .Rows(1).Find(r.Value, , , xlWhole, , 0)

If Not c Is Nothing Then
.Columns(c.Column).Copy
r.PasteSpecial xlPasteValues

End If
Next
Application.CutCopyMode = False
End With


But I also need to add another criteria. basically, if a cell contains a particular text, then only copy those rows
 
Upvote 0

Forum statistics

Threads
1,216,753
Messages
6,132,514
Members
449,732
Latest member
Viva

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top