简体   繁体   中英

Grouping by year in pivot vba

I'm trying to create a pivot table in vba with a field that groups dates by month/year; the Date field runs successfully, but when I add the code to group it by month/year, it gives me an "object required error". How should I fix this?

With ActiveSheet.PivotTables("APivotTable").PivotFields("Date")
.Orientation = xlColumnField
'Error is here
.LabelRange.Group Start:=True, End:=True, _
Periods:=Array(False, False, False, False, True, False, True)
.Position = 1
End With

try this after End with line.

'Change Range("A5") as per your requirement
Range("A5").Group Start:=True, End:=True, Periods:=Array(False, False, False, _
    False, True, False, True)

I ran into this problem myself and was looking for a solution. While Maddy's answer is correct, I really dislike the idea of using a hard coded range instead of the OP's approach of using names.

OP's approach was almost correct. Some additional sleuthing led me to realize the issue is that the Group method must be used on the data of the field you are trying to group, and the OP was using the method on the label of the field.

The solution is very easy. Just move the range being grouped by one cell - from the label to the data using Cells :

.LabelRange.Cells(2,1).Group Start:=True, End:=True, _
Periods:=Array(False, False, False, False, True, False, True)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM