Tuesday, June 26, 2018

Excel VBA: Insert or duplicate column to the left or right of selected cell

Public Sub InsertColumnToTheLeft()
    ActiveCell.EntireColumn.Insert
End Sub

Public Sub InsertColumnToTheRight()
    ActiveCell.Offset(, 1).EntireColumn.Insert
End Sub

Public Sub DuplicateColumnToTheLeft()
    ActiveColumn = ActiveCell.column
    InsertColumnToTheLeft
    CopyColumn ActiveColumn + 1, ActiveColumn
End Sub

Public Sub DuplicateColumnToTheRight()
    ActiveColumn = ActiveCell.column
    InsertColumnToTheRight
    CopyColumn ActiveColumn, ActiveColumn + 1
End Sub

Public Sub CopyColumn(SourceColumn, TargetColumn)
    FinalRow = Cells(Rows.Count, SourceColumn).End(xlUp).Row
    
    For Row = 1 To FinalRow
        Cells(Row, TargetColumn).Value = Cells(Row, SourceColumn).Value
    Next
End Sub

No comments:

Post a Comment