0

I'm creating a PivotTable in Excel using VBA. One of the fields is a time value (formatted as "hh:mm:ss"), and I want the row labels to show each hour (e.g., 00:00, 01:00, 02:00), not every minute.

Here's the relevant part of my code:



With ptHour
        ' Filtros
        .PivotFields("Vehicle id").Orientation = xlPageField
        .PivotFields("Type").Orientation = xlPageField
        .PivotFields("Confirmation").Orientation = xlPageField
        
        .PivotFields("Fecha").Orientation = xlColumnField
        
        .PivotFields("hour").Orientation = xlRowField

        .AddDataField .PivotFields("Vehicle id"), "count of Vehicle ID", xlCount
        
        On Error Resume Next
       .PivotFields("hour").LabelRange.Group _
            Start:=TimeValue("00:00:00"), _
            End:=TimeValue("23:59:59"), _
            By:=TimeValue("01:00:00")
        On Error GoTo 0
End With

The source data in column K is formatted as "hh:mm:ss" using:

wsGuardian.Range("K6:K" & LastFila).NumberFormat = "hh:mm:ss"

However, the PivotTable still shows every minute (e.g., 08:01, 08:02, etc.) instead of grouping by hour.

1
  • 6
    Can you add a calculated column to your source data? Commented Nov 14 at 16:50

1 Answer 1

0

Excel does have a functionality to do it:

Where to find it

Which in VBA translates into the Range.Group method

It is used when selecting the first data cell of your time column (i.e. the one right under the header) in that fashion (as per the doc, the third parameter in the Periods array is the hours, but you may want to group by day, month and year too if you manipulate datetimes):

Sub Group()
    ActiveSheet.PivotTables(1).RowRange.Cells(2, 1).Group Start:=True, End:=True, _
        Periods:=Array(False, False, True, False, False, False, False)
End Sub

And to ungroup:

Sub Ungroup()
    ActiveSheet.PivotTables(1).RowRange.Cells(2, 1).Ungroup
End Sub

From there, adapt the code to get the right column from the RowRange in your sheet and possibly format the numbers to suit the display you want to have.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.