Vba Insert Columns Based on Cell Value

Ben AFF

Board Regular
Joined
Sep 21, 2023
Messages
54
Office Version
  1. 365
Platform
  1. Windows
Hi, Im working on inserting columns based on cell value on the header row.
My bit of code (below) it is supposed to iterate over all columns header row and every instance it finds "YEAR" insert a column.
However it does not work as I intended and it inserts a big number of columns before the first occurrence of "YEAR" and then stops.

Can someone please explain why? Im more interested in understanding why this not work as I intended. Much thanks in advance.

VBA Code:
Sub ColumnInsert()

  Dim k As Integer

  LC = Cells(1, Columns.Count).End(xlToLeft).Column
  For k = 2 To LC
    If Cells(1, k).Value = "Year" Then
    Cells(1, k).EntireColumn.Insert
    End If
  Next k

End Sub
 

Excel Facts

Remove leading & trailing spaces
Save as CSV to remove all leading and trailing spaces. It is faster than using TRIM().
When inserting (or deleting) columns/rows when you have an end point, you need to start from that end and work your way to the start, like this:

VBA Code:
Option Explicit
Sub ColumnInsert()
    Dim LC As Long, k As Long
    
    LC = Cells(1, Columns.Count).End(xlToLeft).Column
    For k = LC To 2 Step -1
        If Cells(1, k).Value = "Year" Then Cells(1, k).EntireColumn.Insert
    Next k
End Sub
 
Upvote 0
Solution

Forum statistics

Threads
1,215,073
Messages
6,122,977
Members
449,095
Latest member
Mr Hughes

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top