如何找到最大值VBA 中给定范围内两个值的绝对顺序差

How to find the max. absolute sequential difference of two values in a given range in VBA

我有一个特定的范围,例如 B2-I2(可以变化),其中包含值,例如 1、2、4、5、34、4、23、12。目的是让一个宏在执行函数时找到给定范围内的最大绝对差异。在上面的示例中,最大的 abs。差异将是 30(如 34-4)。

尝试:

Option Explicit

Sub test()

    Dim i As Long, y As Long, ValueArr As Long, ValueY As Long, MaxDiff As Long
    Dim arr As Variant

    With ThisWorkbook.Worksheets("Sheet1")

        arr = Application.Transpose(.Range("B2:I2").Value)

        For i = LBound(arr) To UBound(arr)

            ValueArr = Abs(arr(i, 1))

            For y = 2 To 9

                ValueY = Abs(.Cells(2, y).Value)

                If ValueArr - ValueY > MaxDiff Then
                    MaxDiff = ValueArr - ValueY
                End If

            Next y

        Next i

        MsgBox MaxDiff

    End With

End Sub

您似乎想要找到最大的顺序差异,如果是这样,试试这个...

Public Function GetLargestDifference(ByVal objCells As Range) As Double
    Dim objCell As Range, i As Long, dblThisDiff As Double, arrValues()

    ' Put the (potentially) non sequential set of cells into a one dimensional array.
    For Each objCell In objCells
        ReDim Preserve arrValues(i)
        arrValues(i) = objCell.Value
        i = i + 1
    Next

    ' Now process that array and check for the max difference.
    For i = 0 To UBound(arrValues) - 1
        dblThisDiff = arrValues(i) - arrValues(i + 1)
        If dblThisDiff > GetLargestDifference Then GetLargestDifference = dblThisDiff
    Next
End Function

...非数值没有错误检查,但您可以根据需要添加。

如果您需要进行绝对检查,请替换此行 ...

dblThisDiff = arrValues(i) - arrValues(i + 1)

...有了这个...

dblThisDiff = Abs(arrValues(i) - arrValues(i + 1))