Generate excel files based on the values of a column

ppoulimen

New Member
Joined
Jun 29, 2020
Messages
4
Office Version
  1. 2016
Hi all,
I have an excel file with two sheets 'Data' , 'Template'

The 'Data' sheet has data in cells A4:AA6608.
In column C, I have sorted the names of companies (but they are not unique).

Moreover, I have a 'Template' sheet with header in A1:AA1

I have a button in 'Data' sheet and I want to generate one excel file
with template header and values of this specific company
for each unique company name (column C).

Could you help me please do this give me some tips how to begin ..

Thanks in advance
 

Excel Facts

Wildcard in VLOOKUP
Use =VLOOKUP("Apple*" to find apple, Apple, or applesauce
My code is as follow but it does not work .. I get error files (generated)

VBA Code:
Sub GenerateReports()
    Dim My_Range As Range
    Dim FieldNum As Long
    Dim FileExtStr As String
    Dim FileFormatNum As Long
    Dim CalcMode As Long
    Dim ViewMode As Long
    Dim ws2 As Worksheet
    Dim myPath As String
    Dim foldername As String
    Dim folderPath As String
    Dim Lrow As Long
    Dim cell As Range
    Dim CCount As Long
    Dim WSNew As Worksheet
    Dim ErrNum As Long

    
    Set My_Range = Range("A3:AA" & LastRow(ActiveSheet))
    My_Range.Parent.Select

    If ActiveWorkbook.ProtectStructure = True Or _
       My_Range.Parent.ProtectContents = True Then
        MsgBox "Sorry, not working when the workbook or worksheet is protected", _
               vbOKOnly, "Copy to new workbook"
        Exit Sub
    End If

    FieldNum = 1

    'Turn off AutoFilter
    My_Range.Parent.AutoFilterMode = False
    
    'Set the file extension/format
    If Val(Application.Version) < 12 Then
        'You use Excel 97-2003
        FileExtStr = ".xls": FileFormatNum = -4143
    Else
        'You use Excel 2007-2013
        If ActiveWorkbook.FileFormat = 56 Then
            FileExtStr = ".xls": FileFormatNum = 56
        Else
            FileExtStr = ".xlsx": FileFormatNum = 51
        End If
    End If
    
     'Change ScreenUpdating, Calculation, EnableEvents, ....
    With Application
        CalcMode = .Calculation
        .Calculation = xlCalculationManual
        .ScreenUpdating = False
        .EnableEvents = False
    End With
    ViewMode = ActiveWindow.View
    ActiveWindow.View = xlNormalView
    ActiveSheet.DisplayPageBreaks = False

    'Delete the sheet RDBLogSheet if it exists
    On Error Resume Next
    Application.DisplayAlerts = False
    Sheets("RDBLogSheet").Delete
    Application.DisplayAlerts = True
    On Error GoTo 0

    ' Add worksheet to copy/Paste the unique list
    Set ws2 = Worksheets.Add(After:=Sheets(Sheets.Count))
    ws2.Name = "RDBLogSheet"
    

    folderPath = Application.ActiveWorkbook.Path

    'Create folder for the new files
    foldername = folderPath & "\" & Format(Now, "yyyymmdd") & "\"
    
    On Error Resume Next
    If Right(foldername, 1) <> "\" Then foldername = foldername & "\"
        Kill foldername & "*.*"
        RmDir foldername   'Delete the now empty folder
        MkDir foldername
    On Error GoTo 0

    
    With ws2
        'first we copy the Unique data from the filter field to ws2
        My_Range.Columns(FieldNum).AdvancedFilter _
                Action:=xlFilterCopy, _
                CopyToRange:=.Range("A1"), Unique:=True
                
        'loop through the unique list in ws2 and filter/copy to a new sheet
        Lrow = .Cells(Rows.Count, "C").End(xlUp).Row
        For Each cell In .Range("A3:AA" & Lrow)

            'Filter the range
            My_Range.AutoFilter Field:=FieldNum, Criteria1:="=" & _
            Replace(Replace(Replace(cell.Value, "~", "~~"), "*", "~*"), "?", "~?")

            'Check if there are no more then 8192 areas(limit of areas)
            CCount = 0
            On Error Resume Next
            CCount = My_Range.Columns(1).SpecialCells(xlCellTypeVisible) _
                     .Areas(1).Cells.Count
            On Error GoTo 0
            If CCount = 0 Then
                MsgBox "There are more than 8192 areas for the value : " & cell.Value _
                     & vbNewLine & "It is not possible to copy the visible data." _
                     & vbNewLine & "Tip: Sort your data before you use this macro.", _
                       vbOKOnly, "Split in worksheets"
            Else
                'Add new workbook with one sheet
                Set WSNew = Workbooks.Add(xlWBATWorksheet).Worksheets(1)

                'Copy/paste the visible data to the new workbook
                My_Range.SpecialCells(xlCellTypeVisible).Copy
                With WSNew.Range("A1")
                    ' Paste:=8 will copy the columnwidth in Excel 2000 and higher
                    ' Remove this line if you use Excel 97
                    .PasteSpecial Paste:=8
                    .PasteSpecial xlPasteValues
                    .PasteSpecial xlPasteFormats
                    Application.CutCopyMode = False
                    .Select
                End With

                'Save the file in the new folder and close it
                On Error Resume Next
                WSNew.Parent.SaveAs foldername & _
                                    cell.Value & FileExtStr, FileFormatNum
                If Err.Number > 0 Then
                    Err.Clear
                    ErrNum = ErrNum + 1

                    WSNew.Parent.SaveAs foldername & _
                     "Error_" & Format(ErrNum, "0000") & FileExtStr, FileFormatNum

                    .Cells(cell.Row, "B").Formula = "=Hyperlink(""" & foldername & _
                      "Error_" & Format(ErrNum, "0000") & FileExtStr & """)"

                    .Cells(cell.Row, "A").Interior.Color = vbRed
                Else
                    .Cells(cell.Row, "B").Formula = _
                    "=Hyperlink(""" & foldername & cell.Value & FileExtStr & """)"
                End If

                WSNew.Parent.Close False
                On Error GoTo 0
            End If

            'Show all the data in the range
            My_Range.AutoFilter Field:=FieldNum

        Next cell
        .Cells(1, "A").Value = "Red cell: can't use the Unique name as file name"
        .Cells(1, "B").Value = "Created Files (Click on the link to open a file)"
        .Cells(3, "A").Value = "Unique Values"
        .Cells(3, "B").Value = "Full Path and File name"
        .Cells(3, "A").Font.Bold = True
        .Cells(3, "B").Font.Bold = True
        .Columns("A:B").AutoFit

    End With

    'Turn off AutoFilter
    My_Range.Parent.AutoFilterMode = False

    If ErrNum > 0 Then
        MsgBox "Rename every WorkSheet name that start with ""Error_"" manually" _
             & vbNewLine & "There are characters in the name that are not allowed" _
             & vbNewLine & "in a sheet name or the worksheet already exist."
    End If

    'Restore ScreenUpdating, Calculation, EnableEvents, ....
    My_Range.Parent.Select
    ActiveWindow.View = ViewMode
    ws2.Select
    With Application
        .ScreenUpdating = True
        .EnableEvents = True
        .Calculation = CalcMode
    End With

End Sub


Function LastRow(sh As Worksheet)
    On Error Resume Next
    LastRow = sh.Cells.Find(What:="*", _
                            After:=sh.Range("C3"), _
                            Lookat:=xlPart, _
                            LookIn:=xlValues, _
                            SearchOrder:=xlByRows, _
                            SearchDirection:=xlPrevious, _
                            MatchCase:=False).Row
    On Error GoTo 0
End Function
 
Upvote 0
Using XL2BB, please upload some sample data showing a before and after sequence. Do not upload a picture as we cannot manipulate data in a picture.
 
Upvote 0
My data are as below :
I want based on the values of C to generate new worksheets as
AVI PHARMA SA GREECE.xlsx

ABBVIE HELLAS.xlsx
SHIRE HELLAS.xlsx
FERTILLAND.xlsx
PROPIUS.xlsx
EUMEDICA.xlsx

with the values of these companies

20200630 test v1.xlsm
ABCDEFGHIJKLMNOPQRSTUVWXYZAA
1
2
3REFERENCE_SEMESTERI_HCDEN_TITLEANT_IDANT_NAMEKAK_IDKAK_NAMEEOF_CODE_5EOF_CODE_5_DESCEOF_CODE_9EOF_CODE_9_DESCATC_4ATC_4_DESCRATC_5ATC_5_DESCRG_GENERICFYK_1AFYK_1BQUANTITYTURNOVER_AMOUNTEOPYY_DAPEU_NET_DAPREBATEW_PROFITCLAWBACKREAL_COSTMEAN_PACK_COST
4201920AVI PHARMA SA GREECE1A V.I. PHARMA INTERNATIONAL S.A., GREECE1A V.I. PHARMA INTERNATIONAL S.A., GREECE09708NORBAL097080101NORBAL TAB 10MG/TAB BTx20 (BLIST 1x 20)N05BEAzaspirodecanedione derivativesN05BE01buspironeΝΑΙΟΧΙΟΧΙ2.0386.419,707.608,340,00898,871.821,744.887,732,40
5201920AVI PHARMA SA GREECE1A V.I. PHARMA INTERNATIONAL S.A., GREECE1A V.I. PHARMA INTERNATIONAL S.A., GREECE27191ZORTAL271910103ZORTAL F.C.TAB 50MG/TAB ΒΤx14 (BLISTERS)N06ABSelective serotonin reuptake inhibitorsN06AB06sertralineΝΑΙΟΧΙΟΧΙ4.33913.320,7315.183,246,281.867,373.614,169.695,432,23
6201920AVI PHARMA SA GREECE1A V.I. PHARMA INTERNATIONAL S.A., GREECE1A V.I. PHARMA INTERNATIONAL S.A., GREECE27191ZORTAL271910203ZORTAL F.C.TAB 100MG/TAB ΒΤx14 (BLISTERS)N06ABSelective serotonin reuptake inhibitorsN06AB06sertralineΝΑΙΟΧΙΟΧΙ4.39313.837,9516.237,4645,051.940,443.874,4510.377,522,36
7201920AVI PHARMA SA GREECE1A V.I. PHARMA INTERNATIONAL S.A., GREECE909NOVA LABORATORIES LTD31146XALUPRINE311460101XALUPRINE ORAL.SUSP 20MG/ML 1 φιάλη (γυάλινη) x 100ml + προσαρμογέας φιάλης + 2 σύριγγες (ΡΕΤ) για χορήγηση από στόματοςL01BBPurine analoguesL01BB02mercaptopurineΝΑΙΟΧΙΝΑΙ19339.476,2247.568,710,0011.567,169.666,8926.334,66136,45
8201920ABBVIE HELLAS10ABBVIE ΦΑΡΜΑΚΕΥΤΙΚΗ ΑΝΩΝΥΜΗ ΕΤΑΙΡΕΙΑ9ABBVIE LTD, UNITED KINGDOM24375SYNAGIS243750302SYNAGIS INJ.SOL 100MG/ML BTx1 GLASS VIAL x 1mlJ06BBSpecific immunoglobulinsJ06BB16palivizumabΟΧΙΟΧΙΝΑΙ2013.809,6016.868,800,004.097,403.547,029.224,38461,22
9201920ABBVIE HELLAS10ABBVIE ΦΑΡΜΑΚΕΥΤΙΚΗ ΑΝΩΝΥΜΗ ΕΤΑΙΡΕΙΑ10ABBVIE ΦΑΡΜΑΚΕΥΤΙΚΗ ΑΝΩΝΥΜΗ ΕΤΑΙΡΕΙΑ19276DARONDA192760101DARONDA INJ.SOL 14MG/2,8ML VIAL BTx1 VIALx2,8 MLL02AEGonadotropin releasing hormone analoguesL02AE02leuprorelinΟΧΙΟΧΙΟΧΙ2.225120.951,00114.865,240,0020.088,8229.365,5365.410,8929,40
10201920ABBVIE HELLAS10ABBVIE ΦΑΡΜΑΚΕΥΤΙΚΗ ΑΝΩΝΥΜΗ ΕΤΑΙΡΕΙΑ10ABBVIE ΦΑΡΜΑΚΕΥΤΙΚΗ ΑΝΩΝΥΜΗ ΕΤΑΙΡΕΙΑ24652CHIROCAINE246520208CHIROCAINE IN.SO.CR 5MG/ML AMP BTx10AMPSx10ML (Φύσιγγες από Πολυπροπυλένιο) (Φύσιγγες από Πολυπροπυλένιο)N01BBAmidesN01BB10levobupivacaineΟΧΙΟΧΙΟΧΙ111,8217,090,001,655,0410,4010,40
11201921SHIRE HELLAS764SHIRE HELLAS A.E.472SHIRE PHARMACEUTICALS IRELAND LIMITED, IRELAND31684NATPAR316840401NATPAR PS.INJ.SOL 100MCG/δόση 2 φυσίγγια -γυάλινο (διπλού θαλάμου)H05AAParathyroid hormones and analoguesH05AA03parathyroid hormoneΟΧΙΟΧΙΝΑΙ85476.361,25421.445,300,0014.158,0189.636,82317.650,473.737,06
12201921FERTILLAND100008FERTILLAND PHARMA ΑΝΑΓΝΩΣΤΑΚΟΣ Γ. ΜΟΝ/ΠΗ Ι.Κ.Ε.100342GEDEON RICHTER PLC., BUDAPEST, HUNGARY30840BEMFOLA308400301BEMFOLA INJ.SO.PFS 225 IU/0.375ML BTx1 pre-filled pen + 1 injection needleG03GAGonadotropinsG03GA05follitropin alfaΟΧΙΟΧΙΟΧΙ1.34669.198,2562.076,700,00634,6512.115,6949.326,3636,65
13201921FERTILLAND100008FERTILLAND PHARMA ΑΝΑΓΝΩΣΤΑΚΟΣ Γ. ΜΟΝ/ΠΗ Ι.Κ.Ε.100342GEDEON RICHTER PLC., BUDAPEST, HUNGARY30840BEMFOLA308400501BEMFOLA INJ.SO.PFS 450 IU/0.75 ML BTx1 pre-filled pen + 1 injection needleG03GAGonadotropinsG03GA05follitropin alfaΟΧΙΟΧΙΟΧΙ717.376,016.806,700,0069,102.635,184.102,4257,78
14201921PROPIUS 100016PROPIUS PRIVATE COMPANY (I.K.E)100016PROPIUS PRIVATE COMPANY (I.K.E)27857FERRINEMIA278570101FERRINEMIA IN.SO.CR 20MG/1ML AMP ΒΤx 5AMPSx5MLB03ACIron, parenteral preparationsB03AC02FERRIC HYDROXIDE SUCROSE COMPLEXΝΑΙΟΧΙΟΧΙ1332.538,972.105,600,0016,06140,941.948,6014,65
15201921EUMEDICA100180EUMEDICA S.A., BRUXELLES, BELGIUM100722OXURION NV. BELGIUM30579JETREA305790201JETREA INJ.SOL 0.375MG/0.3ML (1,25MG/ML) BTx1 VIAL x 0,3 MLS01XAOther ophthalmologicalsS01XA22ocriplasminΟΧΙΝΑΙΟΧΙ38.649,138.337,540,0062,2710.334,320,000,00
Data
Cells with Conditional Formatting
CellConditionCell FormatStop If True
Y4:Y10Cell Value<0textNO
S4:S10Cell Value<0textNO
M4:M10Cell Value<0textNO
G5:G10Cell Value<0textNO
G4Cell Value<0textNO
 
Upvote 0
VBA Code:
Option Explicit

Sub NewWS()
    Dim I As Long, lr As Long
    Dim sname As String
    With Sheets("Sheet1")
        Range("C3:C15").AdvancedFilter Action:=xlFilterCopy, CopyToRange:=Range( _
        "AD3"), Unique:=True
        lr = Range("AD" & Rows.Count).End(xlUp).Row
        For I = 2 To lr
            sname = .Range("AD" & I)
            Sheets.Add After:=Sheets(Sheets.Count)
            Sheets(Sheets.Count).Name = sname & ".xlsx"
        Next I
    End With
End Sub
 
Upvote 0
Thanks for your quick reply

I am sorry, I mean new workbooks not sheets.
Moreover, the new sheets with the above code do not contain any data except header.
 
Upvote 0

Forum statistics

Threads
1,214,400
Messages
6,119,288
Members
448,885
Latest member
LokiSonic

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