Hello,
etaf, thats for the pivot table suggestion. I have complimented your original idea with the VBA automation Yasser was looking for.
Yasser,
Place this code in a module in your workbook. Make sure that the file is like the sample. Once the code is in place run the procedure "MainCode"
Option Explicit
Const strSHEET_DATA As String = "Data"
Const strSHEET_DATA_CLEAN As String = "Clean Data"
Sub MainCode()
On Error GoTo Error_Handler
Call TurnExtrasOff
Call CleanUpData
Call CreatePivotTable
Exit_Handler:
Call TurnExtrasOn
Exit Sub
Error_Handler:
MsgBox "There has been an error while trying to run the code", _
vbCritical + vbOKOnly, "Error"
Resume Exit_Handler
End Sub
Private Sub CleanUpData()
Dim shCleanData As Worksheet
Dim shData As Worksheet
' If the sheet clean data exists then remove it.
On Error Resume Next
Application.DisplayAlerts = False
Sheets(strSHEET_DATA_CLEAN).Delete
Application.DisplayAlerts = True
On Error GoTo 0
' Add a new clean data sheet and asign variables.
Set shData = Sheets(strSHEET_DATA)
Set shCleanData = Sheets.Add
shCleanData.Name = strSHEET_DATA_CLEAN
' Copy the data to a clean sheet.
shData.Cells(2, 2).Resize(shData.UsedRange.Rows.Count, 3).Copy _
Destination:=shCleanData.Cells(1, 1)
' Remove the extra spaces.
shCleanData.Cells(2, 2).Resize(shCleanData.UsedRange.Rows.Count, 1).Offset(1).Replace "Paid", ""
shCleanData.Columns("B").SpecialCells(xlCellTypeBlanks).EntireRow.Delete
' Clean up
Set shCleanData = Nothing
Set shData = Nothing
End Sub
Private Sub CreatePivotTable()
Dim shCleanData As Worksheet
Dim pTable As PivotTable
Dim pCache As PivotCache
' Start setting up the variables.
Set shCleanData = Sheets(strSHEET_DATA_CLEAN)
Set pCache = ActiveWorkbook.PivotCaches.Create(xlDatabase, shCleanData.Cells(1, 1).CurrentRegion.Address)
Set pTable = pCache.CreatePivotTable(shCleanData.Range("I1"), "myTable")
With pTable
.PivotFields("Paid").Orientation = xlRowField
.PivotFields("Paid").Position = 1
.PivotFields("Ser.").Orientation = xlRowField
.PivotFields("Ser.").Position = 2
' General settings
.ColumnGrand = False
.RowGrand = False
.ShowDrillIndicators = False
.RowAxisLayout xlTabularRow
' Remove all the subtotals.
.PivotFields("Ser.").Subtotals(1) = False
.PivotFields("Paid").Subtotals(1) = False
.PivotFields("Type").Subtotals(1) = False
' Remove the blue stly in case you dont like it
.TableStyle2 = ""
End With
' Clean up
Set shCleanData = Nothing
Set pTable = Nothing
Set pCache = Nothing
End Sub
Private Sub TurnExtrasOff()
' Turn off the extras to make code run faster.
With Application
.ScreenUpdating = False
.EnableEvents = False
.Calculation = xlCalculationManual
End With
End Sub
Private Sub TurnExtrasOn()
' Turn on the extras.
With Application
.Calculation = xlCalculationAutomatic
.EnableEvents = True
.ScreenUpdating = True
End With
End Sub
Hope this helps
Bookmarks