Ich habe eine Liste der Preise für die verkauften Produkte und die Preisänderungen von der letzten Woche, jetzt berechne ich Prozentsatzänderung und ich schreibe VBA-Codes, um eine Pivot-Tabelle einschließlich der Gruppierung zu erstellen der Prozentbereiche.Benutzerdefinierte Gruppierung von numerischen Werten Pivot mit VBA-Codes
Mit der Hilfe von Kollegen, ich kann Bereiche von 10,0% jedoch muss ich die Codes auf die Prozentsätze unter 0,0% überarbeiten ist eine Gruppe (< 0,0%), mehr als 100,0% (> 100,0%) ist eine Gruppe, und zwischen ihnen, brauche ich Bereiche von 0,0% - 9,9% und 10,0% bis 19,9% und so weiter.
Ich habe die Codes leicht geändert, um meinen Bedürfnissen gerecht zu werden (Ersetze "zu" durch "-"), aber ich fügte nur 0% hinzu, so dass jetzt Bereiche wie 10.0% statt 10% angezeigt werden So gruppiere ich sie.
Option Explicit
Sub GroupPercents()
Dim pt As PivotTable
Dim pf As PivotField
Set pt = ActiveSheet.PivotTables("% Premium Difference") '<= Change as appropriate
Set pf = pt.PivotFields("% Premium Difference from Prior Term2") '<= Change as appropriate
PercentGroupings pf, -1, 1, 0.1
End Sub
Sub PercentGroupings(pf As PivotField, lFrom As Double, lTo As Double, lGroup As Double, Optional sDelim As String = " - ")
Dim pi As PivotItem
Dim sCaption As String
Dim vSplit As Variant
Dim vItem As Variant
Dim i As Long
With Application
.ScreenUpdating = False
.EnableEvents = False
.Calculation = xlCalculationManual
End With
On Error Resume Next
pf.LabelRange.Ungroup
On Error GoTo 0
pf.LabelRange.Group Start:=lFrom, End:=lTo, By:=lGroup
pf.Parent.ManualUpdate = True
'Format so that groupings appear as % values
For Each pi In pf.PivotItems
With pi
If InStr(.Caption, "<") > 0 Then
'Less Than Group
.Caption = "<" & Split(.Caption, "<")(1) * 100 & ".0%"
ElseIf InStr(.Caption, ">") > 0 Then
'Greater Than Group
.Caption = ">" & Split(.Caption, ">")(1) * 100 & ".0%"
Else
sCaption = ""
vSplit = Split(pi.Caption, "--")
If UBound(vSplit) = 1 Then
'Negative numbers
.Caption = vSplit(0) * 100 & ".0%" & sDelim & "-" & vSplit(1) * 100 & ".0%"
Else
'Positive numbers
vSplit = Split(pi.Caption, "-")
If UBound(vSplit) = 1 Then
On Error Resume Next
vSplit(0) = vSplit(0) * 100
vSplit(1) = vSplit(1) * 100
On Error GoTo 0
ElseIf UBound(vSplit) = 3 Then
' There's some kind of bug with Excel's Grouping feature whereby
' the zero grouping sometimes shows as scientific notation e.g. -2.77555756156289E-17
' So we'll test for this, and change it to zero
If IsNumeric(Join(Array(vSplit(2), vSplit(3)), "-")) Then
vSplit(0) = vSplit(1) * -100
vSplit(1) = 0
End If
End If
.Caption = vSplit(0) & ".0%" & sDelim & vSplit(1) & ".0%"
End If
End If
End With
sCaption = Replace$(sCaption, "to", sDelim)
Next pi
pf.Parent.ManualUpdate = False
With Application
.ScreenUpdating = True
.EnableEvents = True
.Calculation = xlCalculationAutomatic
End With
End Sub
Warum ist der delimeter "-"? – SJR