2013-07-05 57 views
2

我試圖根據模板和Excel數據表生成多個發票並將其保存。以下代碼引發了1004錯誤 - 應用程序定義的錯誤或對象定義的錯誤。你能幫忙嗎?我是vba新手。基於模板和數據工作表生成多個發票

Sub AddNew() 
    Dim str1, str2, str3 As String 
    Dim numrows As Integer 
    Dim i As Integer 

    numrows = ActiveWorkbook.Sheets("Rawdata").Range("A" & Rows.Count).End(xlUp).Row - 2 
    MsgBox numrows 
    i = 3 

    While numrows > 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\" & str1 & " " & Format(str2, "mmm") & "-" & Format(str2, "YYYY") & " " & str3 & ".xlsx" 
      .Close SaveChanges:=True 
     End With 

     ActiveWorkbook.Sheets("Invoice").Select 
     Cells.Select 
     Selection.Copy 

     Workbooks.Open ("D:\Nandini\Invoice generation automation\" & str1 & " " &  Format(str2, 
"mmm") & "-" & Format(str2, "YYYY") & " " & str3 & ".xlsx") 

     activeworksheet.Paste 

     numrows = numrows - 1 

     i = i + 1 
    Wend 
End Sub 

回答

0

試試下面的代碼:

Sub AddNew() 
    Dim str1, str2, str3 As String 
    Dim numrows As Integer 
    Dim i As Integer 
    Dim NewBook As Workbook, oWkb As Workbook 

    With ThisWorkbook.Sheets("Rawdata") 
     numrows = .Range("A" & .Rows.Count).End(xlUp).Row - 2 
     i = 3 

     While numrows > 0 
      str1 = .Cells(i, 16).Value 
      str2 = .Cells(i, 1).Value 

      'cannot save filename with backslash 
      str3 = Replace(.Cells(i, 2).Value, "/", "-") 

      Set NewBook = Workbooks.Add 
      With NewBook 
       .Title = "All Invoice" 
       .Subject = "Invoice" 
       .SaveAs Filename:="D:\Nandini\Invoice generation automation\" & str1 & " " & Format(str2, "mmm") & "-" & Format(str2, "YYYY") & " " & str3 & ".xlsx" 
       .Close SaveChanges:=True 
      End With 

      ThisWorkbook.Sheets("Invoice").Cells.Copy 
      Set oWkb = Workbooks.Open("D:\Nandini\Invoice generation automation\" & str1 & " " & Format(str2, "mmm") & "-" & Format(str2, "YYYY") & " " & str3 & ".xlsx") 

      oWkb.ActiveSheet.Range("A1").PasteSpecial 
      numrows = numrows - 1 

      i = i + 1 
     Wend 

    End With 
End Sub 
+0

你能告訴什麼是錯與原來的代碼? – 2013-07-05 11:22:22

+0

是啊!它的工作正常。非常感謝! –

+0

@NandiniJoshi歡迎:) – Santosh