Adding Pivot Table Fields on VBA

CptnDiego

New Member
Joined
Jan 29, 2018
Messages
3
Hello all,

I am new to VBA and I have been trying to generate a Pivot table from the following data base with no luck yet.
DateFund CodeFund CompartmentNumber of UnitsValue of UnitValue of Fund
5/1/18115010500
5/1/1812609540
4/1/18115110510
4/1/1812599531
3/1/1811529468
3/1/1812608480
5/1/182120051000
5/1/18221506900
5/1/18231075750
(...)(...)(...)(...)(...)(...)

<tbody>
</tbody>

Note that Value of Unit = Value of Fund / Number of Units

In my pivot table, I would like variables "Number of Units" and "Value of Fund" to be the sum of all compartments daily which I have already done. And, the tricky part, I would like for "Value of Unit" to show the "Value of the Unit" for the biggest compartment in terms of "Value of the fund" (highlighted in red above). For my example, the result pivot table would look like this:

DateFund CodeFund CompartmentNumber of UnitsValue of UnitValue of Fund
5/1/181211091040
4/1/181211091041
3/1/18121128948
5/1/182136052650
(...)(...)(...)(...)(...)(...)

<tbody>
</tbody>

My code is as follows:

Code:
'Tabla Dinámica: Numero de Unidades, Valor Unidad, Valor Fondo, Número de Inversionistas'
Dim FuenteSht As Worksheet, DestinoSht As Worksheet, DatosFuente As Range, PvtCache As PivotCache, Pvt As PivotTable, DestinoFinal As String, DatosFinal As String, Fecha As String, Sum_NúmUnidades As String, Máx_ValorUnidad As String, Sum_ValorFondo As String, Sum_NúmInv As String, CódigoFondo As String
            
            'Set Source Data'
            Set FuenteSht = Sheets("BaseTotal")
            Set DatosFuente = Sheets("BaseTotal").Range(Cells(5, 2), Cells(LastRow, 19))
            DatosFinal = FuenteSht.Name & "!" & DatosFuente.Address(ReferenceStyle:=xlR1C1)
                
            'Set pivot table sheet and range'
            Set DestinoSht = Sheets("Ajuste_Compartimientos")
            DestinoFinal = DestinoSht.Name & "!" & DestinoSht.Range("D2").Address(ReferenceStyle:=xlR1C1)
                    
            'Make sure each column has a header'
            If WorksheetFunction.CountBlank(DatosFuente.Rows(1)) > 0 Then
                MsgBox "Una de las columnas no tiene encabezado. Por favor Arreglar en la hoja BaseTotal y volver a correr"
                Exit Sub
            End If
                    
            'Set pivot cache from source data'
            FuenteSht.Activate
                Set PvtCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=DatosFinal)
                
            'Create pivot table from pivot cache
            DestinoSht.Activate
                Set Pvt = PvtCache.CreatePivotTable(TableDestination:=DestinoSht.Cells(2, 4), TableName:="Tabla Dinámica")
                    
            'Add fields to pivot table'
            Set Pvt = ActiveSheet.PivotTables("Tabla Dinámica")
                Pvt.PivotFields("Fecha corte").Orientation = xlRowField
                Pvt.PivotFields("Fecha corte").DataRange.Sort Order1:=xlDescending, Type:=xlSortLabels
                Pvt.PivotFields("Cód. Negocio").Orientation = xlPageField
            Sum_NúmUnidades = "Suma Número de Unidades"
                Pvt.AddDataField Pvt.PivotFields("Núm. unidades"), Sum_NúmUnidades, xlSum
            Máx_ValorUnidad = "Máx Valor Unidad"
                Pvt.AddDataField Pvt.PivotFields("Valor unidad para las operaciones del día t"), Máx_ValorUnidad, xlMax
            Sum_ValorFondo = "Suma Valor Fondo"
                Pvt.AddDataField Pvt.PivotFields("Valor fondo al cierre del día t"), Sum_ValorFondo, xlSum
            Sum_NúmInv = "Suma Número Inversionistas"
                Pvt.AddDataField Pvt.PivotFields("Núm. Invers."), Sum_NúmInv, xlSum
                    
            'Choose Fund'
            FuenteSht.Activate
                CódigoFondo = Range("F3")
            DestinoSht.Activate
                ActiveSheet.PivotTables("Tabla Dinámica").PivotFields("Cód. Negocio").CurrentPage = CódigoFondo
                
            'Refresh pivot table'
            DestinoSht.PivotTables("Tabla Dinámica").RefreshTable
                
        'Copy pivot table values an paste in another sheet'
        Dim TablaDinámica As Range
        Set TablaDinámica = DestinoSht.Range(Cells(5, 4), Cells(5, 8).End(xlDown).Offset(-1))
        TablaDinámica.Copy
        Sheets("Fondo_Calificado").Activate
        Range("C15").Select
        Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
        Application.CutCopyMode = False
       
        'Delete pivot table'
        DestinoSht.PivotTables("Tabla Dinámica").TableRange2.Clear


For the moment I´m using the maximum "Value of Unit" as the filtered "Value of Unit". However I would like to filter the "Value of Unit" corresponding to the biggest "Value of Fund" for each day, if this is possible. I have tried various approaches involving calculated pivot fields but have failed.

I hope I have been clear enough on my intentions.

Thanks in advance for your time and patience. Any help is greatly appreciated.

Diego
 

Excel Facts

What does custom number format of ;;; mean?
Three semi-colons will hide the value in the cell. Although most people use white font instead.

Forum statistics

Threads
1,216,084
Messages
6,128,722
Members
449,465
Latest member
TAKLAM

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