如何在较大范围内找到最大的连续n长度范围

时间:2019-07-05 00:51:25

标签: excel vba max user-defined-functions

我正在尝试查找我范围内最大n个长度连续值子集的单元格引用。

之前曾发布过类似的问题,(the link),但是它只返回子集的总和,我将如何找到特定的单元格引用?

例如,如果n = 3,则最大子集范围将为A3:A5

Cell    Value
A1  2
A2  5
A3  8
A4  2
A5  9
A6  7
A7  2
A8  9
A9  5
A10 3

下面是Excel Hero在共享链接上方的代码,该代码返回子集的总和

Function MaxN(n&, r As Range)
    Dim i&, j&, m#, t#, v
    v = r.Value2
    For i = 1 To UBound(v)
        If UBound(v) - i + 1 >= n Then
            t = 0
            For j = i To i + n - 1
                t = t + v(j, 1)
            Next
            If t > m Then m = t
        Else
            Exit For
        End If
    Next
    MaxN = m
End Function

1 个答案:

答案 0 :(得分:0)

使用此功能:

Function MaxN(n&, r As Range)
    Dim i&, j&, m#, t#, v, str
    v = r.Value2


    For i = 1 To UBound(v)
        If UBound(v) - i + 1 >= n Then
            t = 0
            For j = i To i + n - 1
                t = t + v(j, 1)
            Next
            If t > m Then
            m = t
            str = i
            End If
        Else
            Exit For
        End If
    Next
 MaxN = Range(Cells(str, r.Column), Cells(str + n, r.Column)).Address
End Function