找到范围内最高的12个连续值

时间:2016-04-14 13:44:47

标签: excel

我的数据分布在行和列中,我希望找到每个具有最高值的12个单元格的范围。彼此相邻的意思是从左到右,然后从下一行开始。即A5, B5, ..., L5, A6, B6, ...

data

我可以指定所有可能的范围,即A5:L5, B5:A6...总和并进行比较,但这似乎不是一种非常有效的方法。

如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

试一试。您只需突出显示范围,消息框将返回12整数数组的起始位置。

Sub test()

Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual

    Dim rng As Range

    Dim FC As Integer
    Dim LC As Integer
    Dim FR As Integer
    Dim LR As Integer

    Dim r As Integer
    Dim c As Integer
    Dim i As Integer
    Dim j As Integer
    Dim k As Integer
    Dim max As Integer
    Dim maxI As Integer
    Dim maxCol As Integer
    Dim maxRow As Integer

    Dim intArray() As Integer

    Set rng = Selection

    FC = rng.Column
    FR = rng.Row
    LC = FC + rng.Columns.Count - 1
    LR = FR + rng.Rows.Count - 1

    ReDim intArray(1 To (LC * LR))

    i = 1

    For r = FR To LR
        For c = FC To LC
        intArray(i) = Cells(r, c)
        i = i + 1
        Next c
    Next r

    max = 0

    For i = 1 To (UBound(intArray) - 11)
        k = 0
        k = intArray(i)
        For j = 1 To 11
            k = k + intArray(i + j)
        Next j
        If k > max Then
            max = k
            maxI = i
        End If
    Next i

    maxCol = maxI Mod (rng.Columns.Count)
    maxRow = ((maxI - maxCol) / rng.Columns.Count) + 1

    MsgBox ("Max array begins in row " & maxRow & " column " & maxCol)


Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic

End Sub

如果这不对,请告诉我