VBA Excel:IF然后语句运行循环

时间:2013-03-12 19:13:44

标签: vba excel-vba excel

我是VBA的新手但读书要改进。目前,我从列“A”中获取列并使用它们作为标识符在另一列中运行IF ELSEIF语句。

基本上在range(A1:A3)中,每个单元格中存在值“ERIC”[A1 = ERIC,A2 = ERIC ...],而range(B1:B3)中的值将是三个不同的整数值[B1 = 2, B2 = 9 ......]。我需要在范围“ERIC”中找到这些整数的大数,并在单元格(C1)中放置范围“ERIC”的最大值。

然后在range(A4:A6)中重复“Sally”值的过程,该值与整数范围相关(B4:B6)[B4 = 1,B5 = 4 ...]。最大的价值将进入单元格(C4)我有大约40个名字。

请帮忙。谢谢。

1 个答案:

答案 0 :(得分:2)

这应该按照你的要求去做。它假设你所在的Sheet 1,你的名字在Column AColumn 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

<强> BEFORE

enter image description here

<强> AFTER

enter image description here