0

我是 VBA 新手,但阅读书籍以提高。目前,我正在从列“A”中获取列,并将它们用作标识符以在另一列中运行 IF ELSEIF 语句。

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

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

请帮忙。谢谢。

4

1 回答 1

2

这应该按照您的要求进行。它假设你在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

在此处输入图像描述

在此处输入图像描述

于 2013-03-12T21:19:01.613 回答