Excel VBA,找出同一组数据下的最小值

时间:2016-12-25 13:20:16

标签: vba excel-vba excel

我想问一下,无论如何都要写一个可以在C列中返回值的VBA,它在B列中同一组的B列中具有最小值

例如,对于下表,输出应该返回种族A的草莓,种族B的橙色和种族C的葡萄。

Col A  |  Col B  |  Col C       
Race A |   12    |  Orange         
Race B |   13    |  Apple     
Race A |   9     |  Strawberry       
Race B |   7     |  Orange     
Race C |   12    |  Strawberry     
Race B |   10    |  Cherry     
Race C |   5     |  Grapes     

4 个答案:

答案 0 :(得分:0)

我没有玩很多,可能会有例外,但它适用于你的例子:

=MATCH(MIN(IF($A$1:$A$7=A12;$B$1:$B$7));$B$1:$B$7;0)

使用CTRL + SHIFT + ENTER

输入数组公式

enter image description here

答案 1 :(得分:0)

你可以使用这个功能:

Function GetFruit(race As String) As String
    Dim cell As Range

    With CreateObject("Scripting.dictionary")
        For Each cell In Range("A1", Cells(Rows.count, 1).End(xlUp))
            If .item(cell.Value) = "" Then
                .item(cell.Value) = cell.Offset(, 1) & "|" & cell.Offset(, 2).Address
            ElseIf cell.Offset(, 1).Value < CInt(Split(.item(cell.Value), "|")(0)) Then
                .item(cell.Value) = cell.Offset(, 1) & "|" & cell.Offset(, 2).Address
            End If
        Next cell
        GetFruit = Split(.item(race), "|")(0)
    End With
End Function

答案 2 :(得分:0)

下面的代码(VBA解决方案)放在您的Worksheet_Change事件中(在工作表中,您有数据)。 修改D列中的值后,代码会在列B中搜索与帖子中的条件匹配的最小值。

将结果返回到E列

<强>代码

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)

Dim LastRow As Long, RowFound As Long
Dim MinVal, Rng As Range, cell As Range

' run this code once you modify a value in Column D
If Target.Column = 4 Then
    ' find last row with data in Column A
    LastRow = Cells(Rows.Count, "A").End(xlUp).Row

    ' set range
    Set Rng = Range("B1:B" & LastRow)

    MinVal = 100000 ' init value of MinVal

    ' loop through all cells in Range and look for minimum value
    For Each cell In Rng.Cells
        If cell.Offset(0, -1).Value = Target.Value Then
            If cell.Value < MinVal Then
                MinVal = cell.Value
                RowFound = cell.Row
            End If
        End If
    Next cell

    ' Error handling : if there was no match with tha value entered in Column D
    If MinVal = 100000 Then
        Target.Offset(0, 1) = "Race value not found"
    Else
        Target.Offset(0, 1) = Cells(RowFound, 3)
    End If
End If

End Sub

运行此代码几次后的工作表的屏幕截图(在E列中):

enter image description here

答案 3 :(得分:0)

假设您的范围与您提供的一样。你可以在我的样本中命名范围而不是固定一个:

E列中的公式是数组公式: 种族A(D1)的样本将公式复制并粘贴到下面的E1单元格中,当您仍在单元格中时, Shift + Ctrl + 输入输入公式。

D         | E
--------
Race A    | =INDEX(C2:C8,MATCH(D1&MIN(IF(A2:A8=D1,B2:B8)),A2:A8&B2:B8,0))
Race B    | =INDEX(C2:C8,MATCH(D2&MIN(IF(A2:A8=D2,B2:B8)),A2:A8&B2:B8,0))
Race C    | =INDEX(C2:C8,MATCH(D3&MIN(IF(A2:A8=D3,B2:B8)),A2:A8&B2:B8,0))