【问题标题】:Take the average of a filtered column and have the macro display it in a message box取过滤列的平均值,并让宏将其显示在消息框中
【发布时间】:2016-06-13 18:04:10
【问题描述】:

此宏在 Excel 文档中运行并过滤掉 3 行。现在宏在第三行被过滤时停止,但是我想取第三行的平均值,它有一个动态范围,并将它显示在一个消息框中。

Sub PriceVerifyMacro()

    Dim retval

    retval = InputBox("Please Enter The Price Book Header")

    If IsNumeric(retval) = False Then
        MsgBox "You didn't enter a number! Try again"
        Exit Sub
    End If

    ActiveSheet.Range("$A$1:$CL$293662").AutoFilter Field:=19, Criteria1:="=" & retval

    Dim retval1

    retval1 = InputBox("Please Enter The Net Weight")

    If IsNumeric(retval1) = False Then
        MsgBox "You didn't enter a number! Try again"
        Exit Sub
    End If

    ActiveSheet.Range("$A$1:$CL$293662").AutoFilter Field:=40, Criteria1:="=" & retval1

    Dim retval2

    retval2 = InputBox("Please Enter The PO Cost")

    If IsNumeric(retval2) = False Then
        MsgBox "You didn't enter a number! Try again"
        Exit Sub
    End If

    ActiveSheet.Range("$A$1:$CL$293662").AutoFilter Field:=70, Criteria1:="=" & retval2




    If MsgBox("Would you like to reset the filters?", vbYesNo) = vbNo Then Exit Sub

    ActiveSheet.Range("$A$1:$CL$293662").AutoFilter Field:=70
    ActiveSheet.Range("$A$1:$CL$293662").AutoFilter Field:=40
    ActiveSheet.Range("$A$1:$CL$293662").AutoFilter Field:=19
End Sub

【问题讨论】:

  • 好的。 ......以上不起作用吗?您是否收到任何错误,如果有,在哪里?它是否运行,但不完全按照您的意愿运行,等等?请详细说明您的问题/问题,并请阅读How to Ask
  • @BruceWayne 对措辞不当的问题感到抱歉。我试图修改它以明确我想要什么。一切运行良好,我似乎无法找到如何获得动态范围的平均值,而不是找到固定范围的平均值。
  • @trincot 澄清一下,我正在使用大量项目提取,我必须在其中隐藏某些列以使文档更易于查看。我正在尝试获得第 70 行的平均值,即 BR
  • 是否有任何答案解决了您的问题?你能发表评论吗?

标签: vba excel macros average


【解决方案1】:

您可以使用Range.SpecialCells method。在应用第三个过滤器后添加这个(Dim 行当然可以移到顶部):

Dim sum As Double
Dim count As Double
Dim avg As Double
Dim cell As Range

sum = 0
count = 0
avg = 0
For Each cell In Range("BR2:BR" & ActiveSheet.UsedRange.Rows.count).SpecialCells(xlCellTypeVisible)
    sum = sum + cell.Value
    count = count + 1
Next
If count > 0 Then avg = sum / count
MsgBox "Average is " & avg

【讨论】:

    【解决方案2】:

    您需要在代码中间获取它

    ActiveSheet.Range("$A$1:$CL$293662").AutoFilter Field:=70, Criteria1:="=" & retval2
    For Each cell In Range(Cells(1, 70), Cells(293662, 70)).SpecialCells(xlCellTypeVisible) 'this could be improved, why set to 293662?
        'your stuff to get average and msgbox
    Next
     If MsgBox("Would you like to reset the filters?", vbYesNo) = vbNo Then Exit Sub
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-03
      • 1970-01-01
      • 1970-01-01
      • 2019-03-10
      • 2013-03-18
      • 2021-05-11
      • 2023-03-13
      相关资源
      最近更新 更多