我在数组中有几个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然后运行查找功能。有更简单的方法吗?
答案 0 :(得分:1)
这里的挑战是适当的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
如有任何问题,请询问。
的Diedrich