Excel VBA : 출력 별도의 값과 소계
-
05-07-2019 - |
문제
이 양식의 데이터가 있습니다.
Category Source Amount
Dues FTW $100
Donations ODP $20
Donations IOI $33
Dues MMK $124
정렬 순서가 없습니다. 컴파일 시간에는 카테고리가 알려지지 않았습니다. VBA 매크로가 범위를 순환하고 각각의 하위 토탈과 함께 고유 한 값 목록을 출력하기를 원합니다. 위의 데이터의 경우 다음과 같습니다.
Category Total Amount
Dues $224
Donations $55
어떻게 할 수 있습니까? 또한 위의 테이블이 업데이트 될 때마다 매크로를 실행할 수있는 방법이 있습니까? 아니면 사용자가 버튼을 클릭해야합니까?
해결책
내장 된 Excel 기능을 사용하여이를 수행 할 수 있습니다. 루핑에 오랜 시간이 걸리고 루프 할 값이 많으면 문제가 될 수 있습니다.
다음과 같은 것은 피벗 테이블을 만들기 시작할 수 있습니다 ( 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
이것은 소계를위한 것입니다 (나는 피벗 테이블을 훨씬 선호하지만)http://msdn.microsoft.com/en-us/library/aa213577(Office.11).aspx
편집 : 나는 다시 읽고 다음과 같은 생각을 가지고 있습니다. 피벗 테이블을 별도의 시트 (코드를 사용하지 않고)에 설정 한 다음 피벗 테이블이있는 시트에 다음 코드를 넣어 테이블이 시트가 선택 될 때마다 업데이트됩니다.
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
#2 편집 시트의 모든 피벗 테이블을 새로 고칩니다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
링크에는 시트/통합 문서에서 피벗 테이블을 새로 고치는 방법에 대한 여러 옵션이 있습니다.
제휴하지 않습니다 StackOverflow