这应该按照您的要求进行。它假设你在Sheet 1
,你的名字在Column A
,值在Column B
。
Public Sub FindNameAndGreatestValue()
Dim nameColumnRowCount As Integer
Dim nameColumn As Integer
Dim valueColumn As Integer
Dim outputColumn As Integer
Dim currentName As String
nameColumnRowCount = Cells(Rows.Count, 1).End(xlUp).Row
currentName = ""
nameColumn = 1 '1 = A - change this to column that has names
valueColumn = 4 '4 = D - change this to the column that has values
outputColumn = 5 '5 = E - change this to column that should contain output
Dim currentLargestForName As Integer
Dim currentNameStartRow As Integer
currentLargestForName = -999
currentName = Cells(1, nameColumn).Value
currentNameStartRow = 1
Dim currentRow As Integer
For currentRow = nameColumn To nameColumnRowCount + 1
'if last known name is the same as the current row's name
If StrComp(currentName, Cells(currentRow, nameColumn).Value, vbTextCompare) = 0 Then
'if current rows number is larger than the last known largest number
If currentLargestForName < CInt(Cells(currentRow, valueColumn).Value) Then
currentLargestForName = CInt(Cells(currentRow, valueColumn).Value)
End If
Else
'drop into here if the names no longer match, meaning a new name was found.
'output the largest known number from the previous name into the first row of that name
Cells(currentNameStartRow, outputColumn).Value = currentLargestForName
currentNameStartRow = currentRow 'save the row this new name starts at for number output later
currentLargestForName = CInt(Cells(currentRow, valueColumn).Value)
currentName = Cells(currentRow, nameColumn).Value
End If
Next
End Sub
前
![在此处输入图像描述](https://i.stack.imgur.com/A4ebB.png)
后
![在此处输入图像描述](https://i.stack.imgur.com/V726S.png)