title: Excel vba add code to sheet module programmatically
body: <p>How to put the programmatically generated workbook an event code similar to below:</p>
  
  <pre><code>Private Sub Worksheet_Change(ByVal Target As Range)
  
      Dim nextTarget As Range
  
      Set nextTarget = Range(Selection.Address) 'store the next range the user selects
  
      Target.Columns.Select 'autofit requires columns to be selected
      Target.Columns.AutoFit
  
      nextTarget.Select
  End Sub
  </code></pre>