如何将数据透视表列中的所有值除以常量

时间:2018-07-24 05:22:21

标签: excel vba excel-vba pivot pivot-table

我想用一个添加到数据透视表工作表中的常数来缩放(除法,乘以)数据透视表值,如下所示:

enter image description here

我已经使用以下代码解决了自动更新数据透视表值作为原始数据中的值更改的问题:

function getDetail(e){

  $.ajax({
      type: "POST",
      url: "/result/",
      data: {
            'search': $(this).text(),
            'csrfmiddlewaretoken': $("input[name=csrfmiddlewaretoken]").val()
      },
      dataType:'html',
      success: function(data) {
          # Do other stuff
      },
  });

};

我尝试在worksheet_change()方法中简单地执行此操作,但这会导致类型不匹配错误:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    ActiveWorkbook.Worksheets("Sheet4").PivotTables(1).PivotCache.Refresh
End Sub

2 个答案:

答案 0 :(得分:1)

这是一种方法。当事件WorkSheet_Change触发时,请检查您的缩放值(在B1中)是否已更改。如果是这样,请重写计算所得的字段:

Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Application.Intersect(Range("B1"), Range(Target.Address)) Is Nothing Then
    ActiveWorkbook.Worksheets("Sheet4").PivotTables(1).CalculatedFields("ScaledField"). _
        StandardFormula = "=Kaina*" & Range("B1").Value
    End If
End Sub

您将需要创建一个名为ScaledField的计算字段(或使用您自己的名称-只需更改代码即可) ,如果您不这样做,则可能需要更改公式不想扩大[Kaina],但要扩大规模。

PS。如果该值不是[Kaina],而是[Kaina Sausis],则该公式将需要用单引号引起来来包装字段名称:

StandardFormula = "='Kaina Sausis'*" & Range("B1").Value

答案 1 :(得分:1)

无法直接在数据透视表中操作数据字段的值(尝试手动更改值或使用VBA会收到错误消息)。

可以覆盖行字段的值,但这有点奇怪(除非您碰巧输入了有效值,否则它们将保持这种状态,并且不再更新)。

要进行计算,您可以添加一个计算字段。如果该值是恒定值,并且不需要从范围中获取该值,则只需手动添加一个计算字段(“分析”>“字段...”>“计算字段...”),然后在公式中输入常量值即可。

不幸的是,计算所得的字段无法引用范围,因此,如果您确实必须在计算所得字段的公式中使用“范围”中的值,则可以使用此VBA代码(它会添加计算所得的字段或更新如果该字段已经存在,则使用公式,如果值不恒定,则将使用该值):

' You prolly have to call this only once as you are using a constant value.
' If not add to your worksheet change event
' Modify hardcoded values if needed
Sub createOrUpdateField()
    Dim fldFormula As String

    ' Construct the formula to use
    fldFormula = "= Kaina Sausis / " & ActiveSheet.Range("B1").Value2

    addOrUpdateCalculatedField _
        ActiveSheet.PivotTables(1), _
        "Kaina Sausis Calc", fldFormula, "0.00"
End Sub

' In case you want to remove the calculated field use this
' Or use the interface (Analyze > Fields ... > Calculated Field...)
Sub deleteField()
    pt.PivotFields("Kaina Sausis Calc").Delete
End Sub

' Add a calculated field to pivot table or update formula if it already exists.
' Args:
'   pt (PivotTable): The pivot table object
'   fldName (String): Name to use for the field
'   fldFormula (String): Formula to use for calculation
'   fldFormat (String): Number format to use
Sub addOrUpdateCalculatedField(pt As PivotTable, fldname As String, _
fldFormula As String, fldFormat As String)
    Dim wks As Worksheet
    Dim ptfld As PivotField

    ' Try to reference the field to check if it already exists
    On Error Resume Next
    Set ptfld = pt.PivotFields(fldname)
    On Error GoTo 0

    If ptfld Is Nothing Then
        ' Field doesn't exist, add it
        Set ptfld = pt.CalculatedFields.Add(name:=fldname, formula:=fldFormula)
        With ptfld
            .Caption = fldname
            .NumberFormat = fldFormat
            .Orientation = xlDataField
            .Function = xlSum
        End With
    Else
        ' Field already exists, change the formula only
        ptfld.StandardFormula = fldFormula
    End If

    Set wks = Nothing
    Set pt = Nothing
    Set ptfld = Nothing
End Sub