数组中各种元素的 Minif

Minif for various elements in an array

我在一个数组中有几个 x 变量,其中一些是重复的,因为它们具有不同的 y 值。使用 excel VBA 我想获得每个 x 变量的最小 y 值。例如来自以下集合

x y
a 2
a 3
a 4
b 1
b 2

我想得到

x y
a 2
a 2
a 2
b 1
b 1

我可以 运行 一个 minif,然后是一个查找函数。有更简单的方法吗?

这里的挑战是适当的 MinIfs 函数。我创建了下面的内容,其中 MinIfs(最小范围,查找范围 1,标准范围 1 [查找范围 1+i,标准范围 1+i])。

定义最小值后,只需遍历 x 列中的每个单元格,测试 a 或 b,然后用 MinIfs 值填充相应的 y 单元格。

     'Define MinIfs function
     Function MinIfs(MinRange As Range, ParamArray Criteria() As Variant) As Variant
            Dim n As Long
            Dim i As Long
            Dim c As Long
            Dim f As Boolean
            Dim w() As Double
            Dim k As Double
            Dim z As Variant

            'Error if less than 1 criteria
            On Error GoTo ErrHandler
            n = UBound(Criteria)
            If n < 1 Then
                'too few criteria
                GoTo ErrHandler
            End If

            'Define k
            k = 0

            'Loop through cells of Min range
            For i = 1 To MinRange.Count

            'Start by assuming there is a match
            f = True

                'Loop through conditions
                For c = 0 To n - 1 Step 2

                    'Does cell in criteria range match condition?
                    If Criteria(c).Cells(i).Value <> Criteria(c + 1) Then
                        f = False
                    End If

                Next c

            'Define z
            z = MinRange

                'Were all criteria satisfied and value to be preserved is numeric?
                If f And IsNumeric(z(i, 1)) Then
                    k = k + 1
                    ReDim Preserve w(k)
                    w(k) = z(i, 1)
                End If

            Next i

            MinIfs = Application.Min(w)

            Exit Function

     ErrHandler:
            MinIfs = CVErr(xlErrValue)

        End Function

有什么问题,欢迎提问。

戴德里希