将单元格值与每列的平均值进行比较

时间:2014-10-05 15:44:03

标签: excel loops excel-vba vba

我正在尝试在vba中为excel准备代码。每个月都有一个值列表,每个月列在一个单独的列中,每个月下面列出了多个值。

我想要做的是改变每个单元格的颜色,其值比月平均值小4倍。到目前为止,我的代码看起来像这样,每个平均值的计算方式就像我想要的那样,但我似乎无法弄清楚如何让它将单元格仅比较一列的平均值,而不是连续地将它们全部比较 - 就像它一样现在

Sub MonthAverage()
    Dim Data As Variant
    Set Data = Selection
    Dim rows As Integer
    Dim columns As Integer

    rows = Data.rows.Count
    columns = Data.columns.Count

    Dim average As Double

    For j = 1 To columns
        average = 0#

        For i = 1 To rows
            average = average + Data.Cells(i, j)
        Next

        average = average / rows

        For Each cell In Data.Cells
            If cell.Value <= average / 4 Then cell.Interior.Color = RGB(0, 0, 255)
        Next

        MsgBox average 'just to make sure I got the averages correctly
    Next
End Sub

1 个答案:

答案 0 :(得分:1)

我修改了您的代码以使用ActiveSheet代替当前Selection。此代码循环遍历ActiveSheet中的每一列,并格式化每个单元格的颜色,该颜色小于平均值的四倍。

Sub MonthAverageV2()
    Dim ws As Worksheet
    Dim ThresholdVal As Double
    Dim i As Integer
    Dim j As Integer
    Dim r As Integer

    Set ws = ActiveSheet

    'Loop columns
    For i = 1 To ws.Cells(1, ws.columns.Count).End(xlToLeft).Column
        r = ws.Cells(ws.rows.Count, i).End(xlUp).Row
        'Column average
        ThresholdVal = Application.WorksheetFunction.average(ws.Range(ws.Cells(2, i).Address & ":" & ws.Cells(r, i).Address)) * 0.25
        Debug.Print ThresholdVal
        'Loop rows
        For j = 2 To r
            If ws.Cells(j, i).Value < ThresholdVal Then
                ws.Cells(j, i).Interior.Color = RGB(0, 0, 255)
            End If
        Next j
    Next i
End Sub

另外,我使用Application.WorksheetFunction.average来计算每列的平均值。