VBA: Split data into multiple worksheets based on column

waxsublime

New Member
Joined
Jul 13, 2013
Messages
17
I'm trying to get this code I found (from How to split data into multiple worksheets based on column in Excel?) to work, but it's giving me an error.

Code:
Sub parse_data()
    Dim lr As Long
    Dim ws As Worksheet
    Dim vcol, i As Integer
    Dim icol As Long
    Dim myarr As Variant
    Dim title As String
    Dim titlerow As Integer
    vcol = 4
    Set ws = Sheets("Sheet1")
    lr = ws.Cells(ws.Rows.Count, vcol).End(xlUp).Row
    title = "A1:I1"
    titlerow = ws.Range(title).Cells(1).Row
    icol = ws.Columns.Count
    ws.Cells(1, icol) = "Unique"
    For i = 2 To lr
    On Error Resume Next
    If ws.Cells(i, vcol) <> "" And Application.WorksheetFunction.Match(ws.Cells(i, vcol), ws.Columns(icol), 0) = 0 Then
    ws.Cells(ws.Rows.Count, icol).End(xlUp).Offset(1) = ws.Cells(i, vcol)
    End If
    Next
    myarr = Application.WorksheetFunction.Transpose(ws.Columns(icol).SpecialCells(xlCellTypeConstants))
    ws.Columns(icol).Clear
    For i = 2 To UBound(myarr)
    ws.Range(title).AutoFilter field:=vcol, Criteria1:=myarr(i) & ""
    If Not Evaluate("=ISREF('" & myarr(i) & "'!A1)") Then Sheets.Add(after:=Worksheets(Worksheets.Count)).Name = myarr(i) & ""
    Else
    Sheets(myarr(i) & "").Move after:=Worksheets(Worksheets.Count)
    End If
    ws.Range("A" & titlerow & ":A" & lr).EntireRow.Copy Sheets(myarr(i) & "").Range("A1")
    Sheets(myarr(i) & "").Columns.AutoFit
    Next
    ws.AutoFilterMode = False
    ws.Activate
End Sub

Any ideas on how to fix this?

Thanks!
 
Last edited:
Hi guys,

I had a question about a macro im busy with. Its for splitting data in rows like the one above.
Here is the macro:
Code:
Sub parse_data()
Dim lr As Long
Dim ws As Worksheet
Dim vcol, i As Integer
Dim icol As Long
Dim myarr As Variant
Dim title As String
Dim titlerow As Integer
vcol = 1        
Set ws = Sheets("Sheet1")        
lr = ws.Cells(ws.Rows.Count, vcol).End(xlUp).Row
title = "A1:C1"           
titlerow = ws.Range(title).Cells(1).Row
icol = ws.Columns.Count
ws.Cells(1, icol) = "Unique"
For i = 2 To lr
On Error Resume Next
If ws.Cells(i, vcol) <> "" And Application.WorksheetFunction.Match(ws.Cells(i, vcol), ws.Columns(icol), 0) = 0 Then
ws.Cells(ws.Rows.Count, icol).End(xlUp).Offset(1) = ws.Cells(i, vcol)
End If
Next
myarr = Application.WorksheetFunction.Transpose(ws.Columns(icol).SpecialCells(xlCellTypeConstants))
ws.Columns(icol).Clear
For i = 2 To UBound(myarr)
ws.Range(title).AutoFilter field:=vcol, Criteria1:=myarr(i) & ""
If Not Evaluate("=ISREF('" & myarr(i) & "'!A1)") Then
Sheets.Add(after:=Worksheets(Worksheets.Count)).Name = myarr(i) & ""
Else
Sheets(myarr(i) & "").Move after:=Worksheets(Worksheets.Count)
End If
ws.Range("A" & titlerow & ":A" & lr).EntireRow.Copy Sheets(myarr(i) & "").Range("A1")
Sheets(myarr(i) & "").Columns.AutoFit
Next
ws.AutoFilterMode = False
ws.Activate
End Sub

The only problem is that when i try to run this macro it doesn't splits the names which are longer then 31 characters. i understand that the sheet names can't be longer then 31 characters. I wanted to know if there is possibility to chagne some in the macro that will give a standard name to the sheet so it wont exceed the 31 characaters. Can somebody help me with this
 
Last edited by a moderator:
Upvote 0

Excel Facts

Format cells as currency
Select range and press Ctrl+Shift+4 to format cells as currency. (Shift 4 is the $ sign).
HI!

This code is really useful for me,
But i've One request, i need some Calculations at the bottom of the data in all sheets,

Please check Screen shot,

Is it possible?
9qdkjw
 
Upvote 0
Do you know what I would need to add to this to remove any illegal characters from the strings and replace them with "_"?

Thanks in advance.

. OK.
. That looks simple enough even for me. I expect your problems are more subtle coming from your actual data as the sample data is very simple and small. But anyways…..
…. If I assume your initial file looks like this with just one sheet in it (or only one with all data in it)…
 
Last edited by a moderator:
Upvote 0
Hi all, I am new to VBA and was wondering if anyone could help, I am trying to get 48 columns of data to save in different csv files. I know this is probably complex but I had an idea of trying to separate each column into individual sheets and then saving these. Also is there a way I could save the subsequent files in an incremental order, ie "cv1.csv" , "cv2.csv" and so on?
Thanks a million and sorry for the hastle, any help is greatly appreciated.
 
Upvote 0
Hi,

I saw this macro on the internet and and the main functions on it are working well. However I need data above it from row 1 to row 10 to be distributed throughout all the worksheets and to also have a subtotal shown for all those distributed worksheets. Is there a way it can be done? This is what I currently have.
Code:
'<<<<  Create a new workbook for every unique value  >>>>>


'This example will create a new folder for you and will create
'a new workbook with the data of every unique value in this folder.
'The workbooks will be saved with the Unique value in the new folder.
'It will also add a worksheet to your workbook named "RDBLogSheet" with
'hyperlinks to the workbooks so it is easy to open the workbooks.
'Every time you run the macro it delete this worksheet first so the information is up to date.


'Note: this example use the function LastRow in the ModReset module
Sub Copy_To_Workbooks()
'Note: This macro use the function LastRow
    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 Lrow As Long
    Dim cell As Range
    Dim CCount As Long
    Dim WSNew As Worksheet
    Dim ErrNum As Long


    'Set filter range on ActiveSheet: A11 is the top left cell of your filter range
    'and the header of the first column, D is the last column in the filter range.
    'You can also add the sheet name to the code like this :
    'Worksheets("Sheet1").Range("A11:D" & LastRow(Worksheets("Sheet1")))
    'No need that the sheet is active then when you run the macro when you use this.
    Set My_Range = Range("A11:M" & 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


    'This example filters on the first column in the range(change the field if needed)
    'In this case the range starts in A so Field:=1 is column A, 2 = column B, ......
    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
        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("BSLSummary").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 = "BSLSummary"


    'Fill in the path\folder where you want the new folder with the files
    'you can use also this "C:\Users\Ron\test"
    MyPath = Application.DefaultFilePath


    'Add a slash at the end if the user forget it
    If Right(MyPath, 1) <> "" Then
        MyPath = MyPath & ""
    End If


    'Create folder for the new files
    foldername = MyPath & Format(Now, "yyyy-mm-dd hh-mm-ss") & ""
    MkDir foldername


    With ws2
        'first we copy the Unique data from the filter field to ws2
        My_Range.Columns(FieldNum).AdvancedFilter _
                Action:=xlFilterCopy, _
                CopyToRange:=.Range("A3"), Unique:=True


        'loop through the unique list in ws2 and filter/copy to a new sheet
        Lrow = .Cells(Rows.Count, "A").End(xlUp).Row
        For Each cell In .Range("A4:A" & 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
 
Last edited by a moderator:
Upvote 0
Hi, I thought to bump this thread even though it is old. Mainly because it is based on this very thread.

Here is my question. I am using the code from the first page, can't remember which post number it was. It is working very well but I am needing to ask if something is possible.

At the store, I am having to use a csv file. I copy it into a worksheet named "raw". I have another worksheet in the same workbook labeled as "lists". I have found and edited another macro to go through the "raw" data and delete rows based on values found in list 1 and list 2. I have used the macro found on this thread (as stated earlier) to split the "raw" data into different worksheets based on column B. I have not used the code that gives an error message nor does it sort but would like this as well.

Can something be added to the macro to automatically rename cells that have "forbidden" text (the actual text is the "/")? I am also needing to have 5 letters added to the names based on 2 other lists in the worksheet "lists"; is this possible to do in this macro?

I am using both Excel 2007 and Excel 2010, depending on which computer is free.

To simplify: 2 worksheets: "Raw" and "Lists"
Cell Value in Column B in the "Raw" Worksheet containing "/" in the name to be replaced
Cell Value in Column B in the "Raw" Worksheet found in List 5 1st column to be replaced by List 5 2nd column
(note: this is because some of the names are too long and need to be abbreviated)
Column B in Worksheet "Raw" to be sorted in alphabetical (ascending).
Rows to be moved to different worksheets based on Cell Value in Column B
Cell Value in Column B matching List 3 in Worksheet "Lists" to have HRDWR added to worksheet name (front)
Cell Value in Column B matching List 4 in Worksheet "Lists" to have JUICE added to worksheet name (front)
New Worksheets to be sorted based on Column C (Quantity on Hand) in Ascending order

Can this be done or do I need to do a new macro with the replace cell values?

Thanks to anyone who can assist

GJ Anderson
 
Upvote 0
Hi all,

I'm using the original code from mirabeau which is working great:

Code:
[COLOR=#333333]Sub columntosheets() [/COLOR]
Const sname As String = "Sheet1" 'change to whatever starting sheet
Const s As String = "A" 'change to whatever criterion column
Dim d As Object, a, cc&
Dim p&, i&, rws&, cls&
Set d = CreateObject("scripting.dictionary")
With Sheets(sname)
    rws = .Cells.Find("*", , , , xlByRows, xlPrevious).Row
    cls = .Cells.Find("*", , , , xlByColumns, xlPrevious).Column
    cc = .Columns(s).Column
End With
For Each sh In Worksheets
    d(sh.Name) = 1
Next sh

Application.ScreenUpdating = False
With Sheets.Add(after:=Sheets(sname))
Sheets(sname).Cells(1).Resize(rws, cls).Copy .Cells(1)
.Cells(1).Resize(rws, cls).Sort .Cells(cc), 2, Header:=xlYes
a = .Cells(cc).Resize(rws + 1, 1)
p = 2
For i = 2 To rws + 1
    If a(i, 1) <> a(p, 1) Then
        If d(a(p, 1)) <> 1 Then
            Sheets.Add.Name = a(p, 1)
            .Cells(1).Resize(, cls).Copy Cells(1)
            .Cells(p, 1).Resize(i - p, cls).Copy Cells(2, 1)
        End If
        p = i
    End If
Next i
Application.DisplayAlerts = False
    .Delete
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End With
Sheets(sname).Activate
 [COLOR=#333333]End Sub[/COLOR]

My question:
A is the criterion column and should remain the criterion column, however I don't want column A to be copied into the newly created sheets. Any thoughts on how to do that?

Eternal gratitude to the pro-user who solves this! :biggrin:
 
Upvote 0
….then simplified without comments etc.


Code:
Sub Staffing_Budget_parse_data_AlanJan2015shg()
 
Dim wks1 As Worksheet: Set wks1 = ThisWorkbook.Worksheets(1)
Dim rws As Long, vLkUpc As Long: vLkUpc = 1
Dim lr As Long: lr = wks1.Cells.Find(What:="*", After:=wks1.Cells(1, 1), Lookat:=xlPart, LookIn:=xlFormulas, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
Dim lshtc As Long: lshtc = wks1.Columns.Count
Dim lc As Long: lc = wks1.Cells(1, lshtc).End(xlToLeft).Column
 
    wks1.Cells(1, lshtc) = "Unique"
        For rws = 2 To lr Step 1
        On Error Resume Next
            If wks1.Cells(rws, vLkUpc) <> "" And Application.WorksheetFunction.Match(wks1.Cells(rws, vLkUpc), wks1.Columns(lshtc), 0) = 0 Then
            wks1.Cells(wks1.Rows.Count, lshtc).End(xlUp).Offset(1) = wks1.Cells(rws, vLkUpc)
            End If
        Next rws
    Dim myarr() As Variant
    myarr() = Application.WorksheetFunction.Transpose(wks1.Columns(lshtc).SpecialCells(xlCellTypeConstants, xlTextValues).Value)
    wks1.Columns(lshtc).Delete
 
        For rws = 2 To UBound(myarr)
        wks1.Range(wks1.Cells(1, 1), wks1.Cells(lr, lc)).AutoFilter Field:=vLkUpc, Criteria1:="" & myarr(rws) & ""
            If Not Evaluate("=ISREF('" & myarr(rws) & "'!A1)") Then
            Sheets.Add(After:=Worksheets(Worksheets.Count)).Name = "" & myarr(rws) & ""
            Else
            Sheets("" & myarr(rws) & "").Move After:=Worksheets(Worksheets.Count)
            End If
        wks1.Range("A" & 1 & ":A" & lr & "").SpecialCells(xlCellTypeVisible).EntireRow.Copy
        Worksheets(myarr(rws)).Range("A1").PasteSpecial Paste:=xlPasteFormulas
        Sheets("" & myarr(rws) & "").Columns.AutoFit
        Next rws
 
wks1.AutoFilterMode = False
End Sub

.. returned file…(XL 2007 .xlsm Newest macros in Module “KaransFinal”
https://app.box.com/s/tzzxyuexlopj4q5nhcbpi59gg7yvf4vs

………………………

Alan….

Hi All, this simplified version works perfect. I was wondering if it is possible to set a limit on how many rows can each work sheet contain? I mean each sheet should contain max 25k of unique rows. I mean sometimes it would have 20k rows because next set of unique values would result in sheet containing more than 25k rows of data.

Is anyone able to figure out a way to code something like this?
 
Upvote 0
The code in Post#4 aimed to name the new sheets after the unique items in Column A.

If any or all of these items have more than 31 characters (say because they contain non-printing characters or other reason) then Excel won't do this.

Neither can the code you initially posted. That code just bypasses the error by including an "On Error Resume Next" line about halfway down, in which case the new sheets are just given sheet numbers.

If you want the code I posted to likewise bypass the error and produce that same result, then likewise just include an "On Error Resume Next" about halfway down (say just before the line "a = .Cells(cc).Resize(rws + 1, 1)").

Personally I prefer to not follow that approach. If there's a potential error, caused by data type or whatever, my preference to see just what that error is and then take remedial action, rather than automatically just bypassing any and all errors.

In your case I had no idea of what type of data you had so, as often when doing this sort of thing, some guesswork was needed as to both your data and the nature of result you wanted.


This worked for me perfectly on Monday. I used the same Macro, the same spreadsheet, with the same info today and it will not work at all. No idea why....it completed the task on Monday in less than 10 seconds...one spreadsheet splint into 50+....today it ran for 20 minutes and nothing, excel stopped

thoughts Mirabeau?
 
Upvote 0

Forum statistics

Threads
1,214,386
Messages
6,119,216
Members
448,876
Latest member
Solitario

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