Excel VBA: salida de valores distintos y subtotales
-
05-07-2019 - |
Pregunta
Tengo datos de este formulario:
Category Source Amount
Dues FTW $100
Donations ODP $20
Donations IOI $33
Dues MMK $124
No hay un orden de clasificación. Las categorías son desconocidas en el momento de la compilación. Quiero que una macro VBA recorra el rango, genere una lista de valores distintos, con los subtotales de cada uno. Para los datos anteriores, se vería así:
Category Total Amount
Dues $224
Donations $55
¿Cómo puedo hacer esto? Además, ¿hay una manera de hacer que la macro se ejecute cada vez que se actualice la tabla anterior, o es necesario que el usuario haga clic en un botón?
Solución
Es posible que desee utilizar una función integrada de Excel para hacer esto. El bucle puede llevar mucho tiempo y ser problemático si tiene muchos valores por recorrer.
Algo como lo siguiente podría comenzar con la creación de una tabla dinámica (de http: //www.ozgrid.com/News/pivot-tables.htm )
Sub MakeTable()
Dim Pt As PivotTable
Dim strField As String
'Pass heading to a String variable
strField = Selection.Cells(1, 1).Text
'Name the list range
Range(Selection, Selection.End(xlDown)).Name = "Items"
'Create the Pivot Table based off our named list range.
'TableDestination:="" will force it onto a new sheet
ActiveWorkbook.PivotCaches.Add(SourceType:=xlDatabase, _
SourceData:="=Items").CreatePivotTable TableDestination:="", _
TableName:="ItemList"
'Set a Pivot Table variable to our new Pivot Table
Set Pt = ActiveSheet.PivotTables("ItemList")
'Place the Pivot Table to Start from A3 on the new sheet
ActiveSheet.PivotTableWizard TableDestination:=Cells(3, 1)
'Move the list heading to the Row Field
Pt.AddFields RowFields:=strField
'Move the list heading to the Data Field
Pt.PivotFields(strField).Orientation = xlDataField
End Sub
Esto es para subtotales (aunque prefiero las tablas dinámicas) http://msdn.microsoft.com/en-us /library/aa213577(office.11).aspx
EDITAR: Lo releí y tengo los siguientes pensamientos. Configure la tabla dinámica en una hoja separada (sin usar ningún código), luego coloque el siguiente código en la hoja que tiene la tabla dinámica para que la tabla se actualice cada vez que se seleccione la hoja.
Private Sub Worksheet_Activate()
Dim pt As PivotTable
'change "MiPivot" to the name of your pivot table
Set pt = ActiveSheet.PivotTables("MyPivot")
pt.RefreshTable
End Sub
Editar # 2 Actualizar todas las tablas dinámicas en la hoja http://www.ozgrid.com/VBA/pivot-table-refresh. htm
Private Sub Worksheet_Activate()
Dim pt As PivotTable
For Each pt In ActiveSheet.PivotTables
pt.RefreshTable
Next pt
End Sub
El enlace tiene múltiples opciones sobre cómo actualizar las tablas dinámicas en la hoja / libro de trabajo.