0

我试图从低于平均值的一维数据范围中选择那些值。

这段代码对吗?我认为我如何将它们放入数组BelowAvg中存在问题......

 Function MoyBelow(data As Range) As Variant     
Dim i As Integer     
Dim N As Long     
Redim BelowAvg() As Variant     
Dim Varian As Double     
Dim Somcar() As Variant          

N=WorksheetFunction.Count(data)     
RendMoy=WorksheetFunction.Average(data)          

    For i=1 To N         
        If data.Cells(i).Value < RendMoy Then             
            BelowAvg(i).Value = data(i).Value         
    End If         
    NB = BelowAvg.Count                  

         For j=1 To NB             
             SumSq= SumSq + (BelowAvg(i) - RendMoy)^2        
         Next j
    Next i


         Varian = SumSq/NB     

End Function
4

1 回答 1

0

这是一个函数,它返回一个双精度数组,其中包含一个范围内低于平均水平的单元格:

Function GetBelowAverageValues(data As Range,RangeAverage As Double) As Double()
Dim FilteredRangeValues As Variant
Dim BelowAverageValuesCount As Long
Dim BelowAverageValues() As Double
Dim i As Long

If data.Cells.Count = 1 Then
    MsgBox "only one cell"
    Exit Sub
End If
data.AutoFilter 1, "<" & RangeAverage
FilteredRangeValues = data.SpecialCells(xlCellTypeVisible)
BelowAverageValuesCount = UBound(FilteredRangeValues)
ReDim BelowAverageValues(1 To BelowAverageValuesCount)
For i = 1 To BelowAverageValuesCount
    BelowAverageValues(i) = FilteredRangeValues(i, 1)
Next i
GetBelowAverageValues = BelowAverageValues
data.AutoFilter
End Function

它使用AutoFilter函数和 SpecialCells 属性来过滤和选择相关的单元格。对于您的用途,您可以这样称呼它:

Sub Test()
Dim DataRange as Range
Dim RangeAverage As Double
Dim BelowAverageValues() As Double
Dim i as Long
Dim Varian As Double

Set DataRange = Selection
RangeAverage = Application.WorksheetFunction.Average(DataRange )
BelowAverageValues = GetBelowAverageValues(DataRange ,RangeAverage)
    For i=1 To Ubound(BelowAverageValues)            
        SumSq= SumSq + (BelowAverageValues(i) - RendMoy)^2        
    Next i
Varian = SumSq/NB
End Sub

这主要是经过测试的,但可能在某处有错误。主要功能经过测试并为我工作。

于 2013-05-04T23:25:11.050 回答