Home > OS >  Copy columns between sheets, if they do not yet exist
Copy columns between sheets, if they do not yet exist

Time:03-25

I'm looking for a way or method to copy (adding new) columns between sheets.

Let me illustrate:

Sheet: template

enter image description here

Sheet: student

enter image description here

Initially I duplicate "Template" and rename it. But when additional tasks are added to "Template" I want to update "Student" minding that I have already changed the content in range B2:D4. So copy/pasting the whole range is not an option.

What's the best way to go about this? First checking if row A in the destination sheet has a value, if not copy/paste that column?

A push in the right direction (or some code to get started on) would be very much appreciated.

CodePudding user response:

You can achieve this by looping true columns headers, given they are in the first row and all tabs are named appropriately:

            Sub AddTask()

            With Application

            .ScreenUpdating = False
            .DisplayAlerts = False
            .AskToUpdateLinks = False
            .DisplayStatusBar = True

            End With

            Dim wb As Workbook: Set wb = ThisWorkbook

            With wb
            Dim LastTemplateCol As Long: LastTemplateCol = .Worksheets("Template").Cells(1, Columns.Count).End(xlToLeft).Column


            For i = 2 To LastTemplateCol

                Dim TempTask As String: TempTask = .Worksheets("Template").Cells(1, i).Value
                Dim LastStudentCol As Long: LastStudentCol = .Worksheets("Student").Cells(1, Columns.Count).End(xlToLeft).Column
                
                For t = 2 To LastStudentCol
                
                Dim StudTask As String: StudTask = .Worksheets("Student").Cells(1, t).Value
                Dim Exists As Boolean: Exists = False
                
                If TempTask = StudTask Then
                Exists = True
                GoTo taskloop:
                Else
                GoTo studloop:
                End If
                
            studloop:
                Next t

            If Exists = False Then

            .Worksheets("Template").Cells(1, i).Columns.EntireColumn.Copy
            .Worksheets("Student").Cells(1, LastStudentCol   1).PasteSpecial
            End If

            taskloop:
            Next i

            End With

            Application.CutCopyMode = False

            End Sub
  • Related