r/excel•
X0bi1e

VBA: Find column based on header, copy (with formatting), and insert to left

solved

Hi again r/excel,

I'm both happy/unhappy to be back... I received quick help on my last stop (which I was very grateful for!), and it solved my problem then. I have another I'm looking for a hand with...

PART 1

I have a spreadsheet with a series of headers, with the last in the series with a label such as "COPY ME". I'm looking to find the location/column containing that header, copy the column, and paste all including formatting to it's left as to maintain ranges I've previously defined. I've attempted to do this with the following, but I am only just starting to learn VBA:

Sub CopyInsertCol()

Dim lastColumn As Long
Dim CheckText As String
Dim CheckRow As Long
Dim FindText As Range
Dim LR As Long

CheckRow = 8 'The row containing my header
CheckText = "COPY ME" 'I want to find this in CheckRow
    
Set FindText = Rows(CheckRow).Find(what:=CheckText, LookIn:=xlValues, lookat:=xlWhole) 'I understand this to be my locator
    If FindText Is Nothing Then Exit Sub

LR = Cells(Rows.Count, FindText.Column).End(xlUp).Row
Columns(LR - 4).Copy

FindText.Offset(, 0).EntireColumn.Insert 'Insert column

Cells(1, LR - 4).PasteSpecial Paste:=xlPasteAll

End Sub

Admittedly, this is mostly cluged together from examples I had found and attempted to dissect syntax from, but I do not think it quite does what I need. This seems to somewhat work, but I'd like a cleaner, more accurate code. The - 4 in lines 14 and 18 are only fudge factors to get what I wanted out of it (using a button to run the macro), so naturally it would be nice to get rid of this.

PART 2

Basically the same as Part 1, but I'm trying to copy 2 columns, and insert to left. Reason being my header is in a merged cell that spans the two I want to copy:

COPYME (These are merged)
FooBar

Again, I want to maintain all formatting and equations.

I've enjoyed going through this sub for tips and tricks, and hopefully you excel guru's can give me a hand yet again. I look forward to your responses!

Posted Apr 15, 2016, 12:50 AM UTC

45
Loading comments…