VBA - 为两列中的每一列找到最大值和最小值

时间:2016-11-27 13:24:55

标签: excel vba excel-vba indexing

我有两列数据为double。 我想创建一个执行此操作的vba脚本:

创建一个临时的第三列,用于存储每行的较低值。

输出第三列的最小值和最大值。

现在问题不在于创建第三列,我希望在内存中完成此操作。

请帮忙 感谢

1 个答案:

答案 0 :(得分:0)

这将显示一个带有最小值的消息框和一个带有最大值的消息框,假设两列是A和B.

Sub MinMax()

    ' Count the number of rows in the first column
    ' Assuming that number of rows in second column equals those in the first column
    HowFar = WorksheetFunction.CountA(Range("A:A"))

    ' Declare an array to store the minimums
    Dim Arr() As Double
    ReDim Arr(HowFar - 2)
    Dim Index As Integer
    Index = 0

    ' Loop through the first and second columns and store the minimums for each row in the array
    Dim i As Integer
    For i = 2 To HowFar

        Minimum = Application.WorksheetFunction.Min(Range("A" & i & ":B" & i))

        Arr(Index) = Minimum
        Index = Index + 1

    Next i

    ' Get the minimum value in the array
    Min = Application.WorksheetFunction.Min(Arr)

    ' Get the maximum value in the array
    Max = Application.WorksheetFunction.Max(Arr)

    ' MsgBox the two values
    MsgBox ("Minimum = " & Min)
    MsgBox ("Maximum = " & Max)

End Sub