【问题标题】:AverageIF in VBA with dynamic range [duplicate]具有动态范围的 VBA 中的 AverageIF [重复]
【发布时间】:2018-11-23 11:12:21
【问题描述】:

我有一个 VBA 代码,它创建一个数据透视表,然后根据动态范围找到平均值(因为数据透视表的大小总是在变化)

我想使用 AVERAGEIF 函数而不是平均值,这样我就可以对所有“>0”的值进行平均。我遇到的问题是 Excel 不允许引号内的引号,所以我不能将条件“>0”放在函数中。我当前的代码是:

Sub BuildLaborTable()
'
'This procedure builds the labor table and finds the average of the rows

ActiveWorkbook.ShowPivotTableFieldList = True
With ActiveSheet.PivotTables("Pivot ZP2P").PivotFields("Notif Service product")
    .Orientation = xlRowField
    .Position = 1
End With

ActiveSheet.PivotTables("Pivot ZP2P").AddDataField ActiveSheet.PivotTables( _
    "Pivot ZP2P").PivotFields("Actual Qty"), "Sum of Actual Qty", xlSum

With ActiveSheet.PivotTables("Pivot ZP2P").PivotFields("Notifctn")
    .Orientation = xlColumnField
    .Position = 1
End With                     

Range("A6").Select
Selection.End(xlToRight).Select
ActiveCell.Offset(0, 1).Select
ActiveCell.FormulaR1C1 = "Average"
ActiveCell.Offset(0, 1).Select
ActiveCell.FormulaR1C1 = "Median"
ActiveCell.Offset(1, -1).Select
ActiveCell.FormulaR1C1 = "=AVERAGE(RC2:RC[-2])"

End Sub

我想使用公式 AVERAGEIF(RC2:RC[-2],">0") ,但问题是这需要引号内的引号,这是不允许的。

【问题讨论】:

  • 为什么不允许引号中的引号?
  • @TimWilkinson 因为他这么说,天啊!! /s :)

标签: vba excel excel-formula


【解决方案1】:

在 VBA 中的公式中使用引号时,只需“加倍”:

ActiveCell.FormulaR1C1 = "=AVERAGEIF(RC2:RC[-2],"">0"")"

【讨论】:

  • 是的!谢谢布鲁斯,我不知道引号中的“> 0””双引号作为选项。这是完美的!
【解决方案2】:

您可以加倍引号以在 VBA 中使用。作为旁注,您可以将很多行放在一起以避免一直使用 select

With Range("A6").End(xlToRight)
    .Offset(0, 1).Value = "Average"
    .Offset(0, 2).Value = "Median"
    .Offset(1, 1).FormulaR1C1 = "=AVERAGEIF(RC2:RC[-2],"">0"")"
End With

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-30
    • 2012-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多