title: Generate multiple invoices based on a template and worksheet of data
body: <p>I am trying to generate multiple invoices based on a template and an excel sheet of data and save it. The following code is throwing me a 1004 error - Application defined or object defined error. Can you please help. I am new to vba.</p>
  
  <pre><code>Sub AddNew()
      Dim str1, str2, str3 As String
      Dim numrows As Integer
      Dim i As Integer
  
      numrows = ActiveWorkbook.Sheets("Rawdata").Range("A" &amp; Rows.Count).End(xlUp).Row - 2
      MsgBox numrows
      i = 3
  
      While numrows &gt; 0
          str1 = ActiveWorkbook.Sheets("Rawdata").Cells(i, 16).Value
          MsgBox (str1)
          str2 = ActiveWorkbook.Sheets("Rawdata").Cells(i, 1).Value
  
          'cannot save filename with backslash
          str3 = Replace(ActiveWorkbook.Sheets("Rawdata").Cells(i, 2).Value, "/", "-")
  
          Set NewBook = Workbooks.Add
          With NewBook
              .Title = "All Invoice"
              .Subject = "Invoice"
              .SaveAs Filename:="D:\Nandini\Invoice generation automation\" &amp; str1 &amp; " " &amp; Format(str2, "mmm") &amp; "-" &amp; Format(str2, "YYYY") &amp; " " &amp; str3 &amp; ".xlsx"
              .Close SaveChanges:=True
          End With
  
          ActiveWorkbook.Sheets("Invoice").Select
          Cells.Select
          Selection.Copy
  
          Workbooks.Open ("D:\Nandini\Invoice generation automation\" &amp; str1 &amp; " " &amp;     Format(str2, 
  "mmm") &amp; "-" &amp; Format(str2, "YYYY") &amp; " " &amp; str3 &amp; ".xlsx")
  
          activeworksheet.Paste
  
          numrows = numrows - 1
  
          i = i + 1
      Wend
  End Sub
  </code></pre>