Multiple Sheet creation based on data in an input work sheet.
1. Consider this below table in a excel sheet. You may
required to separate the data based on the item column and put it in separate
sheet.
Item
|
Count
|
|
AC
|
1
|
|
VN
|
2
|
|
AW
|
3
|
|
XT
|
4
|
|
TU
|
5
|
|
AW
|
6
|
|
AC
|
7
|
|
XT
|
8
|
|
AC
|
9
|
|
VN
|
10
|
|
AW
|
11
|
|
AC
|
12
|
|
VN
|
13
|
|
TU
|
14
|
|
AW
|
15
|
|
2. Create a excel document 2007 save as xyz.xlsm (Macro
enabled excel document)
3. See sample data as below
4. Click on the developer tab that appears on the Top
Menu
5. Click on Insert Control and Click the button icon as in the below screens shot
6. Right click on the button control to see the Assign Macro
as in the below screen shot
7. Click on the
Assign Macro as in the below screen shot and it will popup the popup window as
in the below screen shot
8. Then Click the New button from the above popup and
it will open a macro editor as in the below screen shot.
9. Paste the code in the editor.
10. Finally you can see the result as in the below screen
shot.
Code:
Sub
Button1_Click()
If SheetExists("Sheet2") Then
Exit Sub
End If
Sheets("Sheet1").Copy After:=Sheets("Sheet1")
Sheets(2).Name = "Sheet2"
Sheets("Sheet2").Select
finalRow = ActiveSheet.UsedRange.Rows.Count
'Sort Sheet
ActiveWorkbook.Worksheets("Sheet2").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Sheet2").Sort.SortFields.Add
Key:=Range("A1:A" & finalRow) _
, SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Sheet2").Sort
.SetRange Range("A1:B" & finalRow)
.Header = xlGuess
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
'Delete dummy button
ActiveSheet.Shapes("Button 1").Delete
Dim state As String
For x = 1 To finalRow
LastSheet = Sheets.Count
Sheets("Sheet2").Select
ThisTerr = Range("A" & x).Value
state = Range("A" & x).Value
If Not SheetExists(state) Then
Sheets("Sheet2").Copy After:=Sheets(LastSheet)
Sheets(LastSheet + 1).Name = state
Sheets(state).Select
Sheets(state).Activate
'delete unwanted rows
For y = finalRow To 1 Step -1
If (Range("A" & y).Value <> state) Then
Range("A" & y).EntireRow.Delete
End If
Next y
End If
Next x
Application.DisplayAlerts = False
ActiveWorkbook.Worksheets("Sheet2").Delete
Application.DisplayAlerts = True
End Sub
Function SheetExists(SheetName
As String) As Boolean
' returns TRUE
if the sheet exists in the active workbook
SheetExists = False
On Error GoTo NoSuchSheet
If Len(Sheets(SheetName).Name) > 0 Then
SheetExists = True
Exit Function
End If
NoSuchSheet:
End Function

No comments:
Post a Comment