使用VBA对数值进行分组

时间:2017-10-18 21:18:58

标签: excel vba excel-vba

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

我正在使用vba代码创建一个数据透视表,它将显示价格的范围/组。下面是我目前的代码部分,但由于我无法知道价格的最低和最高变化,因此无法产生预期的结果。对于分组方法,一切都高达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

enter image description here

1 个答案:

答案 0 :(得分:2)

你错误地解释了Start和End参数的作用。您不需要事先知道您的最小和最大数字是什么...因为开始和结束参数是数据外部这些边界被组合在一起的阈值。换句话说,如果你想要100的分组,并希望将-1000以下的任何东西混合在一起,并将任何超过1000的东西混合在一起,你可以使用它:

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

...根据我生成的一些随机数据,它会给你这些分组:

enter image description here

如果您想自动更改此格式以使其显示作为货币值,那么您需要一些代码,这些代码也会智能地在所有相关位置添加$符号,例如: / p>

    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

......这样做:

enter image description here