使用VBA对数值进行分组

我正在对每周销售的产品进行价格检查,每个条目代表从上周到本周的价格变化,因此价值可能是正面的或负面的。

我使用vba代码创build一个数据透视表,它将显示范围/价格组。 下面是我目前的代码部分,但没有产生预期的结果,因为我不知道我的最低和最高的价格变化。 对于分组方法,一切高达999美元(从负数)我想他们$ 100和$ 1000以上任何我想把它作为一个组,并显示为$ 1,000 +。

所以我需要自定义数值分组方面的帮助,并且需要显示范围如$ 100- $ 199和$ 1,000 +。 第一张照片是基于我的代码,第二张图是我希望得到的,我知道总数是不一样的,所以只是得到我的分组方法。

我不确定是否可以使用Case语句或If语句将它们分配到范围中。 如果可以,我如何修改我的代码,以便我可以做这个自定义分组。

  'Group by Dim pf As PivotField Pvt.RowAxisLayout xlTabularRow Set pf = Pvt.PivotFields("$ Premium Difference from Prior Term") pf.LabelRange.Group Start:=-300, End:=5000, By:=100 pf.Caption = "Price Range" 'Filter out blanks in row labels For Each pi In pf.PivotItems Dim LR88, i As Long LR88 = PSheet.Cells(Rows.Count, "B").End(xlUp).Row For i = 3 To LR88 - 1 PSheet.Cells(i, 1).FormulaR1C1 = "=IF(RC[2]="""",""Hide"","""")" Next i Dim rng, mycell As Range Set rng = Range("A:A" & LR88 - 1) For Each mycell In rng.Cells If mycell = "Hide" Then pi.Visible = False Else pi.Visible = True End If Next mycell Next pi 

在这里输入图像说明

你误解了开始和结束参数。 您不需要事先知道您的最小和最大的数字是什么,因为开始和结束参数是这些边界之外的数据被组合在一起的阈值。 换句话说,如果你想要100个分组,并且想要把-1000以下的任何东西合在一起,并且把1000以上的东西合起来,你可以使用这个:

 Set pf = pt.PivotFields("Price Difference") pf.LabelRange.Group Start:=-999, End:=1000, By:=100 pf.Caption = "Price Range" 

…这将给你这些分组,基于我生成的一些随机数据:

在这里输入图像说明

如果你想自动改变这个格式来显示货币值,那么你需要一些代码,在所有相关位置智能地添加$符号,如下所示:

  Sub AmendGroupings() Dim pt As PivotTable Dim pf As PivotField Dim pi As PivotItem Dim sCaption As String Const sDelim = "to" 'Change this if you want to use something other than the English word "to". Set pt = ActiveSheet.PivotTables("PivotTable1") '<= Change as appropriate Set pf = pt.PivotFields("Price Range") '<= Change as appropriate Application.ScreenUpdating = False pf.LabelRange.Group Start:=-1000, End:=1000, By:=100 'Format so that groupings appear as currency values For Each pi In pf.PivotItems sCaption = "$" & pi.Caption sCaption = Replace$(sCaption, "$-", "|") sCaption = Replace$(sCaption, "-", " to $") sCaption = Replace$(sCaption, "to $ to $", "to -$") sCaption = Replace$(sCaption, "|", "-$") sCaption = Replace$(sCaption, "$< to ", "<-") If InStr(sCaption, ">") Then sCaption = Replace$(sCaption, ">", "") & " +" 'sCaption = Replace$(sCaption, "to", sDelim) '<= Uncomment if you want to use a different delimiter sCaption = Replace$(sCaption, "$1000", "$1,000") pi.Caption = sCaption Next pi Application.ScreenUpdating = True End Sub 

…这是这样做的:

在这里输入图像说明