Hi All,
I know there are hundreds of posts asking the same question but none of them seem to help me with my problem.
I am a VBA newbie and I am trying to transfer data from one worksheet (ws1) to another (ws2)based on column headers. The headers are not in the same order in ws2 and there is already existing data in this worksheet - so any data copied and pasted across, needs to be added to the end of the existing data.
So far, I have the following code:
Sub Planttest1()
'
' Planttest1 Macro
'
Dim header As Range, headers As Range
Set headers = Worksheets("ws1").Range("A1:Z1")
For Each header In headers
If GetHeaderColumn(header.Value) > 0 Then
Range(header.Offset(1, 0), header.End(xlDown)).Copy Destination:=Worksheets("ws2").Cells(2, GetHeaderColumn(header.Value))
End If
Next
End Sub
Function GetHeaderColumn(header As String) As Integer
Dim headers As Range
Set headers = Worksheets("ws2").Range("A1:Z1")
GetHeaderColumn = IIf(IsNumeric(Application.Match(header, headers, 0)), Application.Match(header, headers, 0), 0)
End Function
Unfortunately, this code doesn't seem to select all the data I need and it doesn't offest anything (and add it onto the bottom of existing data).
Can anyone help me please?
I know there are hundreds of posts asking the same question but none of them seem to help me with my problem.
I am a VBA newbie and I am trying to transfer data from one worksheet (ws1) to another (ws2)based on column headers. The headers are not in the same order in ws2 and there is already existing data in this worksheet - so any data copied and pasted across, needs to be added to the end of the existing data.
So far, I have the following code:
Sub Planttest1()
'
' Planttest1 Macro
'
Dim header As Range, headers As Range
Set headers = Worksheets("ws1").Range("A1:Z1")
For Each header In headers
If GetHeaderColumn(header.Value) > 0 Then
Range(header.Offset(1, 0), header.End(xlDown)).Copy Destination:=Worksheets("ws2").Cells(2, GetHeaderColumn(header.Value))
End If
Next
End Sub
Function GetHeaderColumn(header As String) As Integer
Dim headers As Range
Set headers = Worksheets("ws2").Range("A1:Z1")
GetHeaderColumn = IIf(IsNumeric(Application.Match(header, headers, 0)), Application.Match(header, headers, 0), 0)
End Function
Unfortunately, this code doesn't seem to select all the data I need and it doesn't offest anything (and add it onto the bottom of existing data).
Can anyone help me please?