0

I am trying to populate multiple sheets based on the given data (attached Samplesheet SampleSheet.xlsx) as per the below rules:

Exact Data

  1. Customer Code is the primary key, there should be each sheet for each unique customer code.
  2. The new sheets should be named as "CustomerCode_Leads"
  3. Every worksheet should have same headers.

I have started up with a logic and build a code behind but am lacking the knowledge on how to read the customer code data line by line, copy the rows with the same customer code and paste it in the sheet based on unique customer code.

Code written so far:

Sub Test()
    Dim ws1 As Worksheet
    Set ws1 = ThisWorkbook.Worksheets("Data")
    ws1.Copy ThisWorkbook.Sheets(Sheets.Count)
    
    Selection.AutoFilter
    Selection.End(xlDown).Select
    ActiveCell.Offset(1, 0).Select
    ActiveCell.EntireRow.Select
    Selection.Delete Shift:=xlUp
    Application.Goto Reference:="R2C2"
    ActiveCell.EntireColumn.Select
    
    Selection.Copy
    Sheets.Add After:=ActiveSheet
    ActiveSheet.Paste
    Application.CutCopyMode = False
    ActiveSheet.Range("$A$1:$A$5000").RemoveDuplicates Columns:=1, Header:=xlYes
    
    Dim CurSheet As Worksheet
    Dim Source As Range
    Dim c As Range

    Set CurSheet = ActiveSheet
    Set Source = Selection.Cells
    Application.ScreenUpdating = False

    For Each c In Source
        sName = Trim(c.Text)
        If Len(sName) > 0 Then
                Worksheets.Add After:=Worksheets(Worksheets.Count)
                ActiveSheet.Name = sName + "_Leads"
        End If
    Next c
    
End Sub

Output Desired: Output

Can someone advise how to read the data row by row and paste it in a new worksheet named "CustomerCode_Lead" where "CustomerCode" is a variable with some values in the Data sheet.

The algorithm that I am following is:

  1. Copy the datasheet and paste it into a new worksheet

  2. Sort the data in ascending order based on Customer Code (it'll bring all the similar customer code together and ease the row by row reading)

  3. Read the data row by row and copy the entire row and paste into a new sheet until the customer code stays the same, once different code arrives in the next row, it creates a new sheet named "CustomerCode_Leads"

  4. Do the reading of data until the end of the data in the "Data" sheet.

I would absolutely thank you in advance for the help I'll get here from the community. :)

desmond.carros
  • 372
  • 2
  • 21
  • 2
    Please don't post links to files. If you want to give example data make sure to include it into your question. If you want to show something include screenshots. Everything needed to understand your question needs to be in the question itself. Links will disappear soon or later and the question gets useless. Also see [ask]. • I highly recommend to read [How to avoid using Select in Excel VBA](https://stackoverflow.com/questions/10714251/how-to-avoid-using-select-in-excel-vba) and to apply that approach to your code. – Pᴇʜ Feb 02 '21 at 07:15
  • 2
    Also you should ask a more precise quesiton. A list of requirements is not a real question ([Why is “Can someone help me?” not an actual question?](https://meta.stackoverflow.com/a/284237/3219613)). Where exactly did you get stuck or errors? What went wrong? What did stop you from doing it yourself? Where are your difficulties? What have you tried to achieve it? – Pᴇʜ Feb 02 '21 at 07:17
  • @Pᴇʜ : I am on the way to update the question as much as I can. thanks for valuable feedback so far :) – desmond.carros Feb 02 '21 at 07:21
  • 1
    Does this help to answer your question? [VBA Excel filter data and copy to another worksheet](https://stackoverflow.com/questions/33009016/vba-excel-filter-data-and-copy-to-another-worksheet-newbie-alert). The idea would be first to [get all unique values](https://stackoverflow.com/questions/36044556/quicker-way-to-get-all-unique-values-of-a-column-in-vba) of your customer code column. And then filter your sheet `Data` for each of that unique codes and copy that to a new sheet. Give that a try, this should work. – Pᴇʜ Feb 02 '21 at 07:25
  • @Pᴇʜ : Thanks for taking time, Although, my criteria is to fetch rows with unique customer codes copy the data and paste it in a new worksheet named with same customer code. The above suggestion is to copy the data starting with a set word in a column. :) the logic behind is a bit different. Thanks for validating it at the first go, appreciate that – desmond.carros Feb 02 '21 at 07:31
  • 1
    Actually that is exactly what you need to do: Get a list of unique customer IDs, loop through that list of IDs, for each ID filter your data sheet. Then copy the filered data to a new sheet and name it using the ID. The two links have everything you need. – Pᴇʜ Feb 02 '21 at 07:34
  • @Pᴇʜ : The logic seems fine, a quick question, In my code, I am already finding the unique values and pasting them in another worksheet, however, I've never worked on looping the data due to which I am getting confused on "Filtering the data and copying the data to another sheet" link that you have shared. Apologies if I am not able to explicitely show the void through my question. – desmond.carros Feb 02 '21 at 07:46
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/228139/discussion-between-desmond-carros-and-p). – desmond.carros Feb 02 '21 at 07:48

1 Answers1

1

This is all you need:

  1. Get all unique values of customer ID column
  2. Filter data and copy to another sheet

It could look like below:

Option Explicit

Public Sub SplitDataByCustomerIntoSheets()
    Dim wsData As Worksheet
    Set wsData = ThisWorkbook.Worksheets("Data")
    
    Dim LastRow As Long
    LastRow = wsData.Cells(wsData.Rows.Count, "A").End(xlUp).Row
    
    'creat unique list of customer codes (https://stackoverflow.com/questions/36044556/quicker-way-to-get-all-unique-values-of-a-column-in-vba)
    Dim UniqueValues() As Variant
    UniqueValues = wsData.Range("A2:A" & LastRow).Value
    
    Dim dict As Object
    Set dict = CreateObject("Scripting.Dictionary")
    
    Dim iRow As Long
    For iRow = 1 To UBound(UniqueValues)
        dict(UniqueValues(iRow, 1)) = Empty
    Next
    
    UniqueValues = WorksheetFunction.Transpose(dict.Keys())
    
    
    'check if filter was already set
    If wsData.FilterMode = False Then
        wsData.Range("A1").AutoFilter
    Else
        wsData.ShowAllData
    End If
    
    Dim CustomerID As Variant
    For Each CustomerID In UniqueValues 'loop through all customer IDs
        With wsData.Range("A1:B" & LastRow) 'make sure to adjust B to the last column of your data
            .AutoFilter Field:=1, Criteria1:=CustomerID 'filter by customer ID
            
            'create a new sheet as last sheet and name it by customer ID
            Dim NewSheet As Worksheet
            Set NewSheet = ThisWorkbook.Worksheets.Add(After:=ThisWorkbook.Worksheets(ThisWorkbook.Worksheets.Count))
            NewSheet.Name = CustomerID & "_Leads"
            
            'copy visible cells of filtered data to new sheet
            .SpecialCells(xlCellTypeVisible).Copy NewSheet.Range("A1")
        End With
    Next CustomerID
End Sub

Data sheet:

enter image description here

It will create a sheet for each customer ID like this:

enter image description here

Pᴇʜ
  • 56,719
  • 10
  • 49
  • 73
  • Thanks @Peh, I checked the logic works only for the sample data set you have created, but it's creating 300+ pages (Duplicate pages too), for example, for customer ID (as shown in my Sample set) it is creating 3 sheets for 10404860, any idea how it is not picking unique value? – desmond.carros Feb 02 '21 at 08:08
  • 1
    Did you adjust this `UniqueValues = wsData.Range("A2:A" & LastRow).Value` column to your customer ID column? And did you adjust the field number in `.AutoFilter Field:=1, Criteria1:=CustomerID` to the column number of your customer ID? – Pᴇʜ Feb 02 '21 at 08:18
  • Yes, I did, somehow it is not responding as it should, let me re-run it. Marking this answer as correct as of now! :) – desmond.carros Feb 02 '21 at 08:21
  • It is not populating the data, for example, it created the sheet 1, but the values are blank. – desmond.carros Feb 02 '21 at 08:22
  • 1
    @desmond.carros Actually it is hard to tell where you went wrong without more details. Probably ask a new question showing what you did exactly, if you still get stuck. • If you ask a new question make sure your screenshots contain the column letters A, B, … – Pᴇʜ Feb 02 '21 at 08:25