检查是否MAX并重命名组

时间:2016-10-13 10:14:11

标签: excel-vba excel-formula vba excel

我有以下简化数据:

GroupName    Word    Value    isMaxInGroup

group1      foobar    100    
group1      foobar1   200     1
group2      fox       15      1
group3      snake     18    
group3      bear      25    
group3      bird      100     1

如果此值是当前组的最大值,我必须将A列(GroupName)中的值更改为B列(Word)的值。

例如,请在更改后查看下一个表格:

GroupName    Word    Value    isMaxInGroup

foobar1     foobar     100    
foobar1     foobar1    200    1
fox         fox        15     1
bird        snake      18    
bird        bear       25    
bird        bird       100    1

我试图使用纯VLOOKUP,但我认为这是错误的方式,我需要使用其他东西。 我需要使用哪些公式组合,或者最好通过VBA做什么?

2 个答案:

答案 0 :(得分:1)

如果我们假设组名称在列A中,而列B中的单词,而值在C列中,那么以下数组D2中的strong>公式应该可以解决问题:

=INDEX($B$2:$B$11,MATCH(A2&MAX(IF($A$2:$A$11=A2,$C$2:$C$11)),$A$2:$A$11&$C$2:$C$11,0))

只需在单元格D2中输入此公式,然后将其复制到其余行。

请注意,这是一个数组公式,因此必须使用Ctrl + Shift + Enter输入。如果输入正确,您将在公式栏中看到以下内容:

{=INDEX($B$2:$B$11,MATCH(A2&MAX(IF($A$2:$A$11=A2,$C$2:$C$11)),$A$2:$A$11&$C$2:$C$11,0))}

注意公式周围的两个弯曲括号。这是Excel确认此公式被评估为数组公式。

答案 1 :(得分:0)

所以,换句话说,这是VBA中的简单解决方案:

Sub foobar()
    Dim j As Integer: j = 0
    For i = 2 to 5
        If Cells(i, 1).Value <> Cells(i + 1, 1).Value Then
            Cells(i, "a").Value = Cells(i, "b").Value
        Else
            Do
                j = j + 1
            Loop While Cells(i + j, "d") <> "1"
            groupName = Cells(i + j, "b").Value
            Range("a" & i & ":a" & (i + j)).Value = groupName
        End If
        j = 0
    Next i
End Sub