title: How to refer to VBProject in a different xlsm Workbook?
body: <p>I need to write a macro that will create a new workbook <code>test.xlsm</code> and assign a <code>vb</code> code to it's first sheet (Sheet1). </p>
  
  <pre><code> Sub AddCode()
          Dim wb As Workbook
          Set wb = Workbooks.Add
          Dim ws As Worksheet
          Set ws = wb.Worksheets(1)
  
          Dim code As String
          code = "Sub test()" &amp; vbCrLf &amp; MsgBox "Test" &amp; vbCrLf &amp; "End Sub"
          Dim lineCount As Integer
  
          With wb.VBProject.VBComponents(ws.Name).CodeModule
              lineCount = .CountOfLines
              If lineCount &gt; 0 Then
                  .DeleteLines 1, lineCount
              End If
              .AddFromString code
          End With
  
        wb.Save FileName:="C:\Users\Owner\Desktop\test.xlsm", FileFormat:=52
        wb.Close
      End Sub
  </code></pre>
  
  <p>I get <code>subscript out of range</code> error . I presume that I am referring to the wrong vb project</p>
  
  <p>(PS: by "assigning a code to it's first sheet" I mean the following: <code>Right Click on the Sheet1 -&gt; View Code -&gt; Paste my code to the Module   )</code></p>