获取已过滤列的平均值,并将宏显示在消息框中

时间:2016-06-13 18:04:10

标签: excel vba excel-vba macros average

此宏运行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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

您需要在代码中间获取它

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