首页 > 解决方案 > 如何在满足 VBA 函数中另一个范围的条件的范围内平均可见/过滤的单元格?

问题描述

我对此很陌生,所以我在这段代码上遇到了一些麻烦,希望能得到一些帮助。目标是在满足另一个范围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

谢谢!

标签: excelvbaaverage

解决方案


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

您似乎只知道 IC 是否在 BU 内一次。在找到 IC 后继续寻找 IC,您的原始循环可能已经覆盖了所需的结果。

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

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

推荐阅读