VBA code required

Marky_B

New Member
Joined
Feb 4, 2020
Messages
39
Office Version
  1. 365
  2. 2016
Platform
  1. Windows
Good evening all,
first off thank you for any help, given. I'm after automating invoices from 2 registers.
The setup is I have 2 workbooks [Register_1] and [Register_2] with 5 sheets in each [Week_1] [Week_2] [Week_3] [Week_4] [Week_5], and 1 workbook [Master] with sheet [Invoice] macros enabled to pull data from the other 2 workbooks all saved in the same folder. What I need help with is the following
  • I would like code to search [Register_1] sheet [Week_1] for a surname in cell range {A8-A95} and forename cell range {B8-B95} if match found then
    • copy cell {A1} to workbook [Master] sheet [Invoice] cell {B13}
    • copy total for week to workbook [Master] sheet [Invoice] cell {C13}
    • repeat for [Week_2] [Week_3] [Week_4] [Week_5] moving copy down a cell each time in workbook [Master] sheet [Invoice]
    • If no match then end
Hopefully this all makes sense. I wish I could share the project somehow?

Thank you once again for any help
 
@juddaaaa may be away, so I'll see if I can help.

Where he has the sub OtherMacro, replace it with this;

VBA Code:
Sub SearchPupils()

Dim shtPupils As Worksheet, wbMaster As Workbook, rngPupils As Range

Set wbMaster = ThisWorkbook

Set shtPupils = wbMaster.Worksheets("Pupils")

Set rngPupils = shtPupils.Range("A3")

Do Until rngPupils.Value = ""

    CopyToMaster FullName:=Trim(rngPupils.Value) & " " & Trim(rngPupils.Offset(0, 1).Value)

    Set rngPupils = rngPupils.Offset(1, 0)
Loop

End Sub

change the "set wbMaster = ThisWorkbook" line if the workbook you're putting this code in is not the Master workbook.

It appears you have the export invoice, clean and reset for the next name all sorted out, so you just needed the code to read down the list of pupils, and invoke @juddaaaa 's main routine for each name.
 
Upvote 0

Excel Facts

How to total the visible cells?
From the first blank cell below a filtered data set, press Alt+=. Instead of SUM, you will get SUBTOTAL(9,)
Thank you for the code. However when I run it, it saves each new invoice number as a file but every invoice is blank?? I'm now confused. the code is below. Also for each "Surname" "Forename" if finds could you get it to copy and paste it to cell B9 on the "Invoice" sheet in workbook "Master". Thanks again

Sub SearchPupils()
Dim shtPupils As Worksheet, wbMaster As Workbook, rngPupils As Range
Set wbMaster = ThisWorkbook
Set shtPupils = wbMaster.Worksheets("Pupils")
Set rngPupils = shtPupils.Range("A3")

Do Until rngPupils.Value = ""
CopyToMaster FullName:=Trim(rngPupils.Value) & " " & Trim(rngPupils.Offset(0, 1).Value)
Set rngPupils = rngPupils.Offset(1, 0)
Loop
End Sub
Sub CopyToMaster(FullName As String)
Dim fso As Object, fldr As Object, fl As Object
Dim cc As Range
Dim sht As Worksheet
Dim InRegister As String
Dim nr As Long

Application.ScreenUpdating = False

Set fso = CreateObject("Scripting.FileSystemObject")
Set fldr = fso.GetFolder(ThisWorkbook.Path)
nr = 13
For Each fl In fldr.Files
If InStr(fso.GetBaseName(fl), "Register_") Then
With Workbooks.Open(fl.Path, True, True)
For Each sht In .Sheets
For Each cc In sht.Range("B8:B95")
If Join(Array(cc.Value, cc.Offset(, -1).Value), " ") = FullName Then
With ThisWorkbook
.Activate

With .Sheets("Invoice")
.Activate
.Range("B" & nr).Select

With ActiveCell
.Value = sht.Range("A2")
.Offset(, 1) = sht.Range("O" & cc.Row)

InRegister = Left(.Value, Len(.Value) - (Len(.Value) - InStrRev(.Value, " Week") + 1))
.Offset(, 2) = Sheets("Home").Range("M3:M4").Find(What:=InRegister, LookIn:=xlValues).Offset(, 1)

.Offset(1).Select
End With
End With
End With

nr = nr + 1
Exit For
End If
Next cc
Next sht

.Close _
SaveChanges:=False
End With
End If
Next fl
Application.ScreenUpdating = True

' Copy Invoive to a new workbook
Dim NewFN As Variant
Sheets("Invoice").Select
ActiveSheet.Copy
NewFN = "C:\Project\Invoices\Inv" & Range("E9").Value & ".xlsx"
ActiveWorkbook.SaveAs NewFN, FileFormat _
:=xlOpenXMLWorkbook
ActiveWorkbook.Close
NextInvoice
Sheets("Home").Select
Range("A1").Select

End Sub
 
Upvote 0
FatBoyClam's code is almost there, but he's got the names the wrong way round.

It will be actually searching for Smith John instead of John Smith

Put this in place of OtherMacro
VBA Code:
Sub SearchPupils()

    Dim cc As Range
  
    With Sheets("Pupils")
        For Each cc In .Range("A3", "A" & .Cells(.Rows.Count, "A").End(xlUp).Row)
            CopyToMaster _
                FullName:=Join(Array(Trim(cc.Offset(, 1)), Trim(cc)), " ")
        Next cc
    End With

End Sub
 
Upvote 0
That's fantastic now it pulls the data. is there a way it can pull the searched name i.e. "John" "Smith" to cell "B9" on the invoice at the same time it pulls the other data?
 
Upvote 0
could someone please comment each part / line of the vba code so I can better understand it? I could also add to it if needed. Juddaaaa you have been fantastic at helping with this project, thank you
 
Upvote 0
That's fantastic now it pulls the data. is there a way it can pull the searched name i.e. "John" "Smith" to cell "B9" on the invoice at the same time it pulls the other data?
could someone please comment each part / line of the vba code so I can better understand it? I could also add to it if needed. Juddaaaa you have been fantastic at helping with this project, thank you
VBA Code:
Sub CopyToMaster(FullName As String)

    '// Declare some variables
    Dim fso As Object, fldr As Object, fl As Object
    Dim cc As Range
    Dim sht As Worksheet
    Dim InRegister As String
    Dim nr As Long
  
    '// Turn off Screen Updating
    Application.ScreenUpdating = False
    
    '// Create objects to work with File System
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set fldr = fso.GetFolder(ThisWorkbook.Path)
    
    '// Set Number of first output row in Invoice
    nr = 13

    '// Loop through each file in the folder whos name begins with "Register_"
    '// and then search Range B8:B95 of each sheet in those files for the value
    '// passed in as FullName
    For Each fl In fldr.Files
        If InStr(fso.GetBaseName(fl), "Register_") Then
            With Workbooks.Open(fl.Path, True, True)
                For Each sht In .Sheets
                    For Each cc In sht.Range("B8:B95")
                        If Join(Array(cc.Value, cc.Offset(, -1).Value), " ") = FullName Then
                            With ThisWorkbook
                                .Activate
                                
                                '// Fill out the Invoice with information found in the files
                                With .Sheets("Invoice")
                                    .Activate
                                    .Range("B9") = FullName '// INSERT NAME UNDER BILL TO
                                    .Range("B" & nr).Select '// SELECT FIRST OUTPUT ROW
                                                                
                                    With ActiveCell
                                        .Value = sht.Range("A2") '// DESCRIPTION
                                        .Offset(, 1) = sht.Range("O" & cc.Row) '// NO. OF SESSIONS
                                        
                                        InRegister = Left(.Value, Len(.Value) - (Len(.Value) - InStrRev(.Value, " Week") + 1))
                                       .Offset(, 2) = Sheets("Home").Range("M3:M4").Find(What:=InRegister, LookIn:=xlValues).Offset(, 1) '// COST PER SESSION
                                        
                                        .Offset(1).Select '// MOVE DOWN ONE ROW
                                    End With
                                End With
                            End With
                            
                            nr = nr + 1
                            Exit For
                        End If
                    Next cc
                Next sht
              
                .Close _
                    SaveChanges:=False
            End With
        End If
    Next fl

    '// Turn on Screen Updating
    Application.ScreenUpdating = True
  
End Sub
 
Upvote 0
thanks again. Where abouts would I insert the following code.

Sub PostToRegister()
'Copies Invoice data to the Invoice Register
Dim WS1 As Worksheet
Dim WS2 As Worksheet
Set WS1 = Worksheets("Invoice")
Set WS2 = Worksheets("Register")
'Figures out which row is the next row
NextRow = WS2.Cells(Rows.Count, 1).End(xlUp).Row + 1
'Write the Information to the Register
WS2.Cells(NextRow, 1).Resize(1, 4).Value = Array(WS1.Range("E8"), WS1.Range("E9"), WS1.Range("B9"), Range("InvTotal"))

End Sub
Sub NextInvoice()
'Adds +1 to the invoice then clears all data
Sheets("Invoice").Select
Range("E9").Value = Range("E9").Value + 1
'Range("B8:B10").ClearContents
'Range("B13:D28").ClearContents

End Sub
Sub SaveInvWithNewName()
'Saves the invoice to the invoice folder with invoice name
Dim NewFN As Variant

Application.ScreenUpdating = False
PostToRegister
' Copy Invoice to a new workbook
Sheets("Invoice").Select
ActiveSheet.Copy
'Save active workbook as excel
NewFN = "C:\Project\Invoices\Inv" & Range("E9").Value & ".xlsx"
ActiveWorkbook.SaveAs NewFN, FileFormat:=xlOpenXMLWorkbook
'Save active workbook as PDF
ActiveWorkbook.ExportAsFixedFormat Type:=xlTypePDF, Filename:="C:\Project\Invoices\Inv" & Range("E9").Value & ".pdf"
ActiveWorkbook.Close
NextInvoice
Sheets("Home").Select
Range("A1").Select

End Sub
 
Upvote 0
VBA Code:
Sub SearchPupils()

    Dim cc As Range
    
    With Sheets("Pupils")
        For Each cc In .Range("A3", "A" & .Cells(.Rows.Count, "A").End(xlUp).Row)
            CopyToMaster _
                FullName:=Join(Array(Trim(cc.Offset(, 1)), Trim(cc)), " ")
        Next cc
    End With

End Sub

Sub CopyToMaster(FullName As String)
    '// Declare some variables
    Dim fso As Object, fldr As Object, fl As Object
    Dim cc As Range
    Dim sht As Worksheet
    Dim InRegister As String
    Dim nr As Long
  
    '// Turn off Screen Updating
    Application.ScreenUpdating = False
    
    '// Create objects to work with File System
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set fldr = fso.GetFolder(ThisWorkbook.Path)
    
    '// Set Number of first output row in Invoice
    nr = 13

    '// Loop through each file in the folder whos name begins with "Register_"
    '// and then search Range B8:B95 of each sheet in those files for the value
    '// passed in as FullName
    For Each fl In fldr.Files
        If InStr(fso.GetBaseName(fl), "Register_") Then
            With Workbooks.Open(fl.Path, True, True)
                For Each sht In .Sheets
                    For Each cc In sht.Range("B8:B95")
                        If Join(Array(cc.Value, cc.Offset(, -1).Value), " ") = FullName Then
                            With ThisWorkbook
                                .Activate
                                
                                '// Fill out the Invoice with information found in the files
                                With .Sheets("Invoice")
                                    .Activate
                                    .Range("B9") = FullName '// INSERT NAME UNDER BILL TO
                                    .Range("B" & nr).Select '// SELECT FIRST OUTPUT ROW
                                                                
                                    With ActiveCell
                                        .Value = sht.Range("A2") '// DESCRIPTION
                                        .Offset(, 1) = sht.Range("O" & cc.Row) '// NO. OF SESSIONS
                                        
                                        InRegister = Left(.Value, Len(.Value) - (Len(.Value) - InStrRev(.Value, " Week") + 1))
                                       .Offset(, 2) = Sheets("Home").Range("M3:M4").Find(What:=InRegister, LookIn:=xlValues).Offset(, 1) '// COST PER SESSION
                                        
                                        .Offset(1).Select '// MOVE DOWN ONE ROW
                                    End With
                                End With
                            End With
                            
                            nr = nr + 1
                            Exit For
                        End If
                    Next cc
                Next sht
              
                .Close _
                    SaveChanges:=False
            End With
        End If
    Next fl
    
    '// Save Invoice
    SaveInvWithNewName

    '// Turn on Screen Updating
    Application.ScreenUpdating = True
End Sub

Sub SaveInvWithNewName()
    'Saves the invoice to the invoice folder with invoice name
    Dim NewFN As Variant
    PostToRegister
    
    ' Copy Invoice to a new workbook
    Sheets("Invoice").Select
    ActiveSheet.Copy
    
    'Save active workbook as excel
    NewFN = "C:\Project\Invoices\Inv" & Range("E9").Value & ".xlsx"
    ActiveWorkbook.SaveAs NewFN, FileFormat:=xlOpenXMLWorkbook
    
    'Save active workbook as PDF
    ActiveWorkbook.ExportAsFixedFormat Type:=xlTypePDF, Filename:="C:\Project\Invoices\Inv" & Range("E9").Value & ".pdf"
    ActiveWorkbook.Close
    NextInvoice
    Sheets("Home").Select
    Range("A1").Select
End Sub

Sub PostToRegister()
    'Copies Invoice data to the Invoice Register
    Dim WS1 As Worksheet
    Dim WS2 As Worksheet
    
    Set WS1 = Worksheets("Invoice")
    Set WS2 = Worksheets("Register")
    
    'Figures out which row is the next row
    NextRow = WS2.Cells(Rows.Count, 1).End(xlUp).Row + 1
    
    'Write the Information to the Register
    WS2.Cells(NextRow, 1).Resize(1, 4).Value = Array(WS1.Range("E8"), WS1.Range("E9"), WS1.Range("B9"), Range("InvTotal"))

End Sub

Sub NextInvoice()
    'Adds +1 to the invoice then clears all data
    Sheets("Invoice").Select
    Range("E9").Value = Range("E9").Value + 1
    Range("B8:B10").ClearContents
    Range("B13:D28").ClearContents
End Sub
 
Upvote 0
The code works perfectly, Thank you just 1 last request and the project is complete. I need the information from the invoices copied to the register sheet, as in the picture. Because it will run each month is there a way to look on the produced invoice and copy it to the correct pupil / month?
if that makes sense!!
 

Attachments

  • Capture.JPG
    Capture.JPG
    184.3 KB · Views: 3
Upvote 0
Is this a difficult one? I don’t know any other way. Ideas, are welcome

Thanks again
 
Upvote 0

Forum statistics

Threads
1,215,063
Messages
6,122,930
Members
449,094
Latest member
teemeren

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top