如何对满足VBA功能中另一个范围的条件的范围内的可见/过滤单元进行平均?

时间:2018-07-06 18:51:55

标签: excel vba average

我在这方面还很新,所以我在使用此代码时遇到了一些麻烦,希望能得到一些帮助。目标是在满足另一个范围2(即文本)的条件时,对经过过滤/可见的单元格区域取平均值。

到目前为止,我有以下内容:

Function AverVisibleIC(Rg As Range, BU As Range)

Dim xCell As Range
Dim xCount As Integer
Dim xTtl As Double
Dim c As Range
Set BU = Range("B13:B44")

Application.Volatile
Set Rg = Intersect(Rg.Parent.UsedRange, Rg)
For Each xCell In Rg
    If xCell.ColumnWidth > 0 _
      And xCell.RowHeight > 0 _
      And Not IsEmpty(xCell) _
      And IsNumeric(xCell.Value) Then
          xTtl = xTtl + xCell.Value
          xCount = xCount + 1
    End If
Next
    If xCount > 0 Then
        For Each c In BU
        If c.Value = "IC" Then
            AverVisibleIC = xTtl / xCount
             Else
                AverVisibleIC = 0
     End If
         End If
Next
End Function

谢谢!

1 个答案:

答案 0 :(得分:0)

将Rg与使用的范围相交后,根据Rg的剩余大小重置BU范围。

您似乎只知道IC是否在BU内一次。找到集成电路后,继续查找集成电路,您的原始循环可能已经覆盖了预期的结果。

我不知道这是否完美,但也许它更接近您想要达到的目标。

Function AverVisibleIC(Rg As Range, BU As Range)

    Dim xCount As long, xTtl As Double, i as long

    Application.Volatile

    Set Rg = Intersect(Rg.Parent.UsedRange, Rg)
    set bu = bu.cells(1).resize(rg.rows.count, rg.columns.count)

    For i=1 to Rg.cells.count
        If Rg.cells(i).ColumnWidth > 0 _
          And Rg.cells(i).RowHeight > 0 _
          And Not IsEmpty(Rg.cells(i)) _
          And IsNumeric(Rg.cells(i).Value) _
          and cbool(instr(1, bu.cells(i).value2, "IC", vbtextcompare)) Then
              xTtl = xTtl + Rg.cells(i).Value2
              xCount = xCount + 1
        End If
    Next i

    If xCount > 0 Then
         AverVisibleIC = xTtl / xCount
    End If

End Function