列中的五个最大值

时间:2015-10-08 06:25:45

标签: excel vba excel-vba

我的目标是在消息框中列出五个最大的值。但因为我正在使用">" L之前的列中的值不计入La或Lb。例如:

7
8
5
3
6
2

L变为8,但La(第二大)变为6(但应该是7),Lb(第三大)变为{{1} },Lc = 2,Ld = 0

0

我知道无论谁看到这个都有能力用一行代码解决问题,但是,为了教育新手,请不要这样做。

4 个答案:

答案 0 :(得分:3)

您的嵌套If ... Else ...语句可以更容易编写为Select Case statement。它甚至可以提高可读性。

问题是随后的值会覆盖以前的值。在覆盖之前,需要将现有值进一步推送到队列中。虽然下面的代码有点冗长,但它应该充分展示解决方案。

Sub maxtest3()
    Dim L As Variant, a As Range, rng As Range

    Set rng = Range("A1:A" & Cells(Rows.Count, "A").End(xlUp).Row)
    ReDim L(1 To 5)

    For Each a In rng
        Select Case a.Value
            Case Is > L(1)
                L(5) = L(4)
                L(4) = L(3)
                L(3) = L(2)
                L(2) = L(1)
                L(1) = a.Value
            Case Is > L(2)
                L(5) = L(4)
                L(4) = L(3)
                L(3) = L(2)
                L(2) = a.Value
            Case Is > L(3)
                L(5) = L(4)
                L(4) = L(3)
                L(3) = a.Value
            Case Is > L(4)
                L(5) = L(4)
                L(4) = a.Value
            Case Is > L(5)
                L(5) = a.Value
        End Select
    Next a

    MsgBox Join(L, Chr(32))

End Sub

我已将您的L x vars更改为简单的一维数组。这允许使用Join Function来简化字符串连接到MsgBox

答案 1 :(得分:2)

refresh

答案 2 :(得分:1)

Jeeped已经解释了为什么If Block尝试失败的逻辑。
另一方面,由于您使用的是Excel,因此可以使用可用的功能
类似于:

Sub maxtest3()
    Dim L As Integer, La As Integer, Lb As Integer, Lc As Integer, Ld As Integer

    With Application.WorksheetFunction
        L = .Large(Range("A1:A20"), 1)
       La = .Large(Range("A1:A20"), 2)
       Lb = .Large(Range("A1:A20"), 3)
       Lc = .Large(Range("A1:A20"), 4)
       Ld = .Large(Range("A1:A20"), 5)
    End With
    MsgBox (L & " " & La & " " & Lb & " " & Lc & " " & Ld)
End Sub

答案 3 :(得分:1)

我希望这会有所帮助。

Sub maxtest3()

Dim L(4) As Integer
Dim Lp(4) As Integer
Dim i, j As Integer

Dim RC As Boolean

Dim a As Variant

For i = 0 To 4

    L(i) = 0

    For Each a In Range("A1:A20")

        'If the current cell location has been used before sets RC = False
        RC = True
        For j = 0 To i - 1
            If Lp(j) = a.Row Then RC = False
        Next j

        'If the current cell value is greater than the current value in L(i) 
        'AND the location has not been used already, sets L(i) to the current
        'value and sets Lp(i) to the location of the current value
        If a.Value > L(i) And RC = True Then
            L(i) = a.Value
            Lp(i) = a.Row
        End If
    Next
Next i

MsgBox (L(0) & " " & L(1) & " " & L(2) & " " & L(3) & " " & L(4))

End Sub

该程序在五个单独的时间内循环选择范围。每次循环时,选择下一个最大的数字。 L(i)和Lp(i)变量代表五个元素的数组,每个元素将保存您的五个最大数字及其在范围选择中的位置。这允许程序跳过已经选择为更大的数字。

要考虑的事项: 如果相同的数字在值范围内出现不止一次,则可以选择每个实例作为最大的数字'值。

如目前所述,该程序仅考虑正整数。如果范围内的所有数字都是负数,则返回全零。要解决此问题,请将L(i)的初始化值从0更改为-32768(可以存储在整数中的最大负值)