Splitting data into multiple sheets

22strider

Active Member
Joined
Jun 11, 2007
Messages
311
Hello Friends

Could you please help me writing code in VBA for splitting data into multiple sheets?

The split needs to be based on value in one of the columns and the sheet where the data will be sent to should get sheet name same as value in the column. Following data sample may help me explain in a better way:

Following is the input sheet, the data needs to be split based on entry in the column "Job Type".


Excel 2007
ABCD
1Invoice NumberJob TypeInvoice DateAmount
21234Repair04-Apr-13$200
33456Contract Work10-Apr-13$400
47896General23-Apr-13$100
Input Sheet


Following tables are showing data split into multiple sheets and the sheet names are the same as entry under the column "Job Type"


Excel 2007
ABCD
1Invoice NumberJob TypeInvoice DateAmount
21234Repair04-Apr-13$200
Repair



Excel 2007
ABCD
1Invoice NumberJob TypeInvoice DateAmount
23456Contract Work10-Apr-13$400
Contract Work



Excel 2007
ABCD
1Invoice NumberJob TypeInvoice DateAmount
27896General23-Apr-13$100
General


Thanks for your help

Rajesh
 
Bah. By the way you originally worded it I thought you were talking about the reason I didn't include code to double check if a sheet already exists. If you're starting with a blank workbook other than the import sheet, it wouldn't matter. I couldn't see the relation between the two things.

I guess I was stuck on that.... Wrong results is a completely different story. A simple fix none the less.

Code:
Option Explicit
Public Function UniqueItems(ArrayIn, Optional Add2Arr As Variant, Optional count As Variant) As Variant
    
' Function will produce an array of Unique Items in a range or another array.

'Declarations
Dim Unique() As Variant
Dim Element As Variant
Dim i As Long
Dim NumUnique As Long
Dim IsInArray As Boolean

' If 2nd argument is missing, assign default value.
' Add2Arr is if the results will be added to an existing array, rather than
' a new array.
' Like so,  myarray = UniqueItems(Range("A1:B10"), myarray)
' in this case, myarray already contains array data and we will just add the results
' to the end of it.  Argument is optional and will produce a new array if 2nd arguement
' is missing.
If IsMissing(count) Then count = False
If Not IsMissing(Add2Arr) Then
    Unique = Add2Arr
    NumUnique = UBound(Add2Arr) + 1
End If
        
'Loop through the array
For Each Element In ArrayIn
    IsInArray = False
    ' If Arr has not been established, skip the loop
    ' This if line only works with arrays that have been declared
    ' like this.  Dim myarray() as variant
    ' if an array is declared with just Dim myarray as variant
    ' This will not determine if the array has been initialized
    ' it would instead fail.  I have another function altogether
    ' to determine if array's have been initialized, but this works
    ' for a one time use.  The double not states that if it is initialized
    ' it will run the for loop.
    If Not ((Not Unique) = -1) Then
        'Looks at each element of the array it is building (or each element in
        'the existing array if supplied) and determines if the element already
        'exists in the array.
        For i = LBound(Unique) To UBound(Unique)
            If Element = Unique(i) Then
                IsInArray = True
                Exit For
            End If
        Next i
    End If
    'If the element does not exist in the array, we will then add it to the array
    'Also eliminating any empty elements as we only want actual data, not blank data
    If IsInArray = False And Element <> "" Then
        ReDim Preserve Unique(NumUnique)
        Unique(NumUnique) = Element
        NumUnique = NumUnique + 1
        IsInArray = True
    End If
Next Element

'outputs the array, unless count is specified, then it will give a count of
'unique items in the range or array.
If count Then UniqueItems = NumUnique Else UniqueItems = Unique

End Function

Sub Input2Sheets()

'Declarations
Dim lr As Long
Dim i As Long
Dim NewWS As Worksheet
Dim InputSHT As Worksheet
'Sets the input worksheet so we can refer to it by it's short name InputSHT
Set InputSHT = Sheets("Input Sheet")

Dim JobTypeARR As Variant
lr = InputSHT.Range("B" & Rows.count).End(xlUp).Row

'Uses the above function to produce a list of unique job types.
JobTypeARR = UniqueItems(Range("B2", "B" & lr))

'Loop through the job types, create the sheets and move pertinant data to new sheet
For i = LBound(JobTypeARR) To UBound(JobTypeARR)
    'Sets the criteria to use for the Advanced Filter
    InputSHT.Cells(1, "G").Value = InputSHT.Cells(1, "B").Value
    InputSHT.Cells(2, "G").Value = "=" & """" & "=" & JobTypeARR(i) & """"
    
    'Adds the new sheet and names it
    Sheets.Add.Name = JobTypeARR(i)
    'sets New Worksheet so it can be referred to by its short name "NewWS"
    'Since its only used once, its not really needed and can refer to the sheet
    'name directly, but I figured it would be nice to have it if there was
    'anything else you'd like to do with the New worksheet before you moved
    'on to adding the next one.
    Set NewWS = Sheets(JobTypeARR(i))
    
    'Advanced Filter, uses the Criteria range set above to pull all records
    'matching the jobtype.
    InputSHT.Range("A1:D" & lr).AdvancedFilter Action:=xlFilterCopy, _
                        CriteriaRange:=InputSHT.Range("G1:G2"), _
                        CopyToRange:=NewWS.Range("A1:D1"), Unique:=True
Next i

'Clears the criteria range as its not needed afterwards.
InputSHT.Range("G1:G2").ClearContents

End Sub

What changed is this line....

Code:
InputSHT.Cells(2, "G").Value = "=" & """" & "=" & JobTypeARR(i) & """"

Which now sets the criteria formula to ="=JobType" which makes it look at A1 as A1 and not part of A10. There might be a more simplified way of doing it, but that works.
 
Upvote 0

Excel Facts

Test for Multiple Conditions in IF?
Use AND(test, test, test, test) or OR(test, test, test, ...) as the logical_test argument of IF.
Hi guys! I am new here and honestly, this is my first time trying a forum to get help on a task that I need to do so I would appreciate any assistance that I can get. I will be referring to the following image in this post to try and explain what I am looking for.



I need a code that will split this Excel sheet whenever a DATE occurs. So in this case, the code should split the sheet into 2 (because there are 2 dates occurring). The first sheet should include Rows 1-22 and the second sheet should contain Rows 23-45.

This can go on and on for about 60000 Rows. The only criteria that should be met is that a particular sheet should start with the date and end with the row "PLEASE CALL OUR OFFICE"

PLEASE HELP!!! THANKS!!
 
Upvote 0
hi guys! I am new here and honestly, this is my first time trying a forum to get help on a task that i need to do so i would appreciate any assistance that i can get. I will be referring to the following image in this post to try and explain what i am looking for.



i need a code that will split this excel sheet whenever a date occurs. So in this case, the code should split the sheet into 2 (because there are 2 dates occurring). The first sheet should include rows 1-22 and the second sheet should contain rows 23-45.

This can go on and on for about 60000 rows. The only criteria that should be met is that a particular sheet should start with the date and end with the row "please call our office"

please help!!! Thanks!!

it would not let me post the image. Any ideas?????????
 
Upvote 0
zackii,

Welcome to the MrExcel forum.

1. What version of Excel and Windows are you using?

2. Are you using a PC or a Mac?


You are trying to post a picture/graphic. This means that if this was a problem where one needed to use your data, anyone trying to help you would have to enter the data manually. That makes no sense.


Please do not post your questions in threads started by others - - this is known as thread hijacking.

Always start a new thread for your questions and, if you think it helps, provide a link to any other thread as a reference.

Start a new thread for your question and be sure to give it a search friendly title that accurately describes your need.

In your New Thread include:
1. the version of Excel you are using
2. Are you using a PC or a Mac?
3. a screenshot, NOT a picture/graphic, of the raw data, and, worksheet name
4. a screenshot, NOT a picture/graphic, of the results (manually formatted by you for the results you are looking for)


To post a small screen shot try one of the following:

Excel Jeanie
Download

MrExcel HTML Maker
https://onedrive.live.com/?cid=8cffdec0ce27e813&sc=documents&id=8CFFDEC0CE27E813!189

Borders-Copy-Paste
http://www.mrexcel.com/forum/about-board/444901-how-create-table-like-aladin.html#post2198045

To test the above:
Test Here


Or, you can upload your workbook to Box Net,
sensitive data changed
mark the workbook for sharing
and provide us with a link to your workbook.


Then send me a Private Message, with a link to your New Thread, and, I will have a look.
 
Upvote 0

Forum statistics

Threads
1,216,099
Messages
6,128,822
Members
449,470
Latest member
Subhash Chand

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