Transfer Data from Invoice to Worksheet with VBA

Let’s watch the Excel training video before we start understanding the VBA macro code to transfer the data.

Transfer Data from Invoice to Worksheet

How to transfer data from invoice to an Excel worksheet automatically with VBA. Earlier we had learnt how to transfer data from a worksheet to an invoice template. Often we need to create a report from an invoice or purchase order and wish to automate the process completely. 

The macro VBA code does the following:

  • It automatically increases the invoice number by 1 when we open the workbook
  • The invoice data is automatically displayed
  • The payment due date is automatically calculated
  • Important data like invoice number, invoice data, item description, item value and invoice total is transferred to another sheet to create a report. The item value and invoice total is calculated automatically
  • If the user enters no data like quantity or details of the item then the macro exits without saving the data or file
  • At the end of the invoice entry the file is saved in two formats automatically – .xlsx and .pdf

The complete macro code:

Private Sub Workbook_BeforeClose(Cancel As Boolean)
Dim ws1 As Worksheet
Set ws1 = Worksheets(“Invoice”)
Dim ws2 As Worksheet
Set ws2 = Worksheets(“Sheet1”)
Dim count As Long
count = 0

Application.DisplayAlerts = False

For i = 15 To 29
If ws1.Cells(i, 2) = “” Then
count = count + 1
End If
Next i
If count = 15 Then
ActiveWorkbook.Close savechanges = False
Exit Sub
End If

For i = 15 To 29
erow = ws2.Cells(Rows.count, 1).End(xlUp).Offset(1, 0).Row
If ws1.Cells(i, 2) <> “” Then
ws2.Cells(erow, 1) = ws1.Range(“InvoiceNumberDisplay”)
ws2.Cells(erow, 2) = ws1.Cells(3, 2)
ws2.Cells(erow, 2) = Format(ws2.Cells(erow, 2), “mm-dd-yy”)
ws2.Cells(erow, 3) = ws1.Cells(i, 3)
ws2.Cells(erow, 4) = ws1.Cells(i, 5)
End If
Next i
ws2.Cells(erow – 1, 5) = ws1.Range(“InvoiceTotal”)

Dim Path As String
Path = “c:\myinvoices\”
ActiveWorkbook.Save
ActiveWorkbook.ActiveSheet.SaveAs Filename:=Path & Range(“B2″) & ” – ” & Range(“C2”) & “.xlsx”, FileFormat:=51
ActiveWorkbook.ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=Path & Range(“B2″) & ” – ” & Range(“C2”) & “.pdf”, OpenAfterPublish:=False

Application.DisplayAlerts = True
End Sub

Private Sub Workbook_Open()
Range(“InvoiceNumberDisplay”) = Range(“InvoiceNumberDisplay”) + 1
Range(“C3”) = Date
Range(“C4”) = DateAdd(“m”, 1, Range(“B3”))
Range(“B15:D29”) = “”
End Sub