title: How do I insert columns dynamically in Excel?
body: <p>I would like to insert separating columns into an Excel report to make the existing columns easier to view.</p>
  
  <p>The report is created dynamically and I never know how many columns there will be; there could be 5, 10, 17, etc.</p>
  
  <p>The section starts at F and goes to <code>ival=Application.WorksheetFunction.CountIf(range("D2:D" &amp; LastRow), "Other")</code> </p>
  
  <p>So if <code>ival=10</code> then the columns are F G H I J K L M N O, and I need to insert columns between F&amp;G, G&amp;H, H&amp;I, I&amp;J, ... and N&amp;O.</p>
  
  <p>This may be a possibility for inserting columns: <code>Workbooks("yourworkbook").Worksheets("theworksheet").Columns(i).Insert</code></p>
  
  <p>But I'm not sure how to loop through <code>ival</code>.</p>
  
  <pre><code>Sub InsertColumns()
      Dim iVal As Integer
      Dim Rng As range
      Dim LastRow As Long
      Dim i  As Integer
  
      With Sheets("sheet1")
          LastRow = .range("D" &amp; .Rows.Count).End(xlUp).Row
      End With
  
      iVal = Application.WorksheetFunction.CountIf(range("D2:D" &amp; LastRow), "Other")
  
      For i = 7 To iVal - 1
      Workbooks("yourworkbook").Worksheets("theworksheet").Columns(i+1).Insert
      Next i
  
  End Sub
  </code></pre>