0

I tried the below code to copy entire column from one page to other page.

I've common header that is June scattered in the sheet, I want to copy only the columns, with header name as "June" in the separate sheet one after the other.

EG if Col A, C,L,M has column header as June, then on the next sheet these should be only copied as A,B,C,D.

Sheets("sheet1").Select 
June = WorksheetFunction.Match("Description", Rows("1:1"), 0) 

Sheets("sheet1").Columns(June).Copy Destination:=Sheets("sheet2").Range("A1") 
Community
  • 1
  • 1
  • use the `Find` function in row 1, set a `Range`, and if `Find` is successful, get the `Column` property – Shai Rado Jul 28 '17 at 08:16

1 Answers1

1

Following might help:

Option Explicit

Sub Demo()
    Dim srcSht As Worksheet, destSht As Worksheet
    Dim headerRng As Range, cel As Range, copyRng As Range
    Dim lastCol As Long, col As Long

    Set srcSht = ThisWorkbook.Sheets("Sheet1")      'Sheet1
    Set destSht = ThisWorkbook.Sheets("Sheet2")     'Sheet2

    lastCol = srcSht.Cells(1, srcSht.Columns.Count).End(xlToLeft).Column    'last column of Sheet1

    With srcSht
        For Each cel In .Range(.Cells(1, 1), .Cells(1, lastCol))  'loop through each header name in Sheet1
            If cel = "June" Then                            'check header is "June"
                If copyRng Is Nothing Then                  'assign range to copy
                    Set copyRng = .Columns(cel.Column)
                Else
                    Set copyRng = Union(copyRng, .Columns(cel.Column))
                End If
            End If
        Next cel
    End With
    copyRng.Copy destSht.Range("A1")                'copy and paste desired columns
End Sub
Mrig
  • 11,612
  • 2
  • 13
  • 27