How to insert columns dynamically in Excel?

I would like to insert dividing columns in an Excel report to make it easier to view existing columns.

The report is generated dynamically, and I never know how many columns there will be; may be 5, 10, 17, etc.

The section begins with F and goes to ival=Application.WorksheetFunction.CountIf(range("D2:D" & LastRow), "Other")

So, if ival=10 , then the FGH columns are JKLMNO, and I need to insert the columns between F & G, G & H, H & I, I & J, ... and N & O.

It may be the ability to insert columns: Workbooks("yourworkbook").Worksheets("theworksheet").Columns(i).Insert

But I'm not sure how to get through ival .

 Sub InsertColumns() Dim iVal As Integer Dim Rng As range Dim LastRow As Long Dim i As Integer With Sheets("sheet1") LastRow = .range("D" & .Rows.Count).End(xlUp).Row End With iVal = Application.WorksheetFunction.CountIf(range("D2:D" & LastRow), "Other") For i = 7 To iVal - 1 Workbooks("yourworkbook").Worksheets("theworksheet").Columns(i+1).Insert Next i End Sub 
+8
excel-vba excel
source share
2 answers

The code below should work without worrying about ival :

 Sub InsertSeparatorColumns() Dim lastCol As Long With Sheets("sheet1") lastCol = Cells(2, .Columns.Count).End(xlToLeft).Column For i = lastCol To 7 Step -1 .Columns(i).Insert .Columns(i).ColumnWidth = 0.5 Next End With End Sub 
+9
source share

Try the following:

 Sub InsertSeparatorColumns() Dim ws as Worksheet Dim firstCol As String Dim lastRow As Long Dim i As Long Dim howManySeparators As Long Set ws = ThisWorkbook.Sheets("Sheet1") firstCol = "F" lastRow = ws.Range("D" & ws.Rows.Count).End(xlUp).Row howManySeparators = Application.WorksheetFunction.CountIf _ (ws.range("D2:D" & LastRow), "Other") For i = 1 To howManySeparators * 2 Step 2 ws.Range(firstCol & 1).Offset(, i).EntireColumn.Insert Next i End Sub 
+3
source share

All Articles