Sub SHEET1MACINVOICE()
Dim CopyRows As Range
Set SceSht = ActiveSheet
Worksheets.Add
ActiveSheet.Move
Set NewSht = ActiveSheet
NewSht.Range("A1:I1") = Array("Buyer's Reference", "Invoice Number", "REFERENCE", "Description of Goods", "HS Code", "Origin", "Quantity", "@", "Amount")
With SceSht
Set HSC = .Cells.Find(what:="HS Code", LookIn:=xlFormulas, lookat:=xlWhole, searchformat:=False)
Set DLT = .Cells.Find(what:="Detail Line Total", LookIn:=xlFormulas, lookat:=xlWhole, searchformat:=False)
'Determine rows to be copied (uses
Set CopyRows = .Range(.Cells(HSC.Row + 1, HSC.Column + 2), .Cells(DLT.Row - 1, HSC.Column + 2))
On Error Resume Next
Set CopyRows = .Range(.Cells(HSC.Row + 1, HSC.Column + 2), .Cells(DLT.Row - 1, HSC.Column + 2)).SpecialCells(xlCellTypeConstants, 23)
On Error GoTo 0
'Column C reference gets its data from Description of Goods column A:
Intersect(CopyRows.EntireRow, .Columns(1)).Copy NewSht.Range("C2")
'Column D data comes from column B:
Intersect(CopyRows.EntireRow, .Columns(2)).Copy NewSht.Range("D2")
'Copy the next 5 columns:
Intersect(CopyRows.EntireRow, .Columns(HSC.Column).Resize(, 5)).Copy NewSht.Range("E2")
'Buyer's Ref and Invoice no. repeat in columns A and B respectively.
Set TheLastCell = NewSht.Range("A1").SpecialCells(xlCellTypeLastCell)
Set InvNo = .Cells.Find(what:="Invoice Number", LookIn:=xlFormulas, lookat:=xlWhole, searchformat:=False).Offset(2)
InvNo.Copy Range(NewSht.Range("B2"), NewSht.Cells(TheLastCell.Row, "B"))
Set BuyRef = .Cells.Find(what:="Buyer's Reference", LookIn:=xlFormulas, lookat:=xlWhole, searchformat:=False).Offset(1)
BuyRef.Copy Range(NewSht.Range("A2"), NewSht.Cells(TheLastCell.Row, "A"))
'put the total in:
.Cells(DLT.Row, HSC.Column + 4).Copy TheLastCell.Offset(1)
End With
NewSht.Columns("A:I").EntireColumn.AutoFit
'Save and close new Workbook with invoice number an name to the C:\INVOICE folder:
NewSht.Parent.Close True, Filename:="C:\INVOICE\" & InvNo.Value & ".xlsx"
End Sub