查找列表或数组中的最小值,不包括某些元素

时间:2012-10-15 16:16:45

标签: excel vba excel-vba

  • 我有一个变量列表,我需要找到最小值并评估为候选者,以便将不同的相关值增加1。
  • 但是,不应考虑已经等于100的变量(以百分比表示),因为它们不能超过100。

(确定变量是a,增量值是b)

a1 = 0.5,
a2 = 0.6,
a3 = 0.2,
myArray(0) = a1
myArray(1) = a2
myArray(2) = a3
b1 = 0,
b2 = 10,
b3 = 100

我当前的代码

If b1 = 100 Then
myArray(0) = null (empty, something to remove it from consideration in min function)
End IF
If b2 = 100 Then
myArray(1) = null
End IF
If b3 = 100 Then
myArray(2) = null
End IF
minvalue = Application.WorksheetFunction.Min(myArray(0), myArray(1), myArray(2))
'also tried: minvalue = Application.WorksheetFunction.Min(myArray)
If minvalue = a1 Then
b1 = b1 +1
Else If minvalue = a2 Then
b2 = b2 +1
Else If minvalue = a3 Then
b3 = b3 +1
End IF

我希望代码注意到即使a3是最小值,b3也不能再增加,所以下一个最低值是a1,因此b1增加1.

此功能在常规Excel电子表格中有效。我可以创建一个值列表,然后在它们下面的单元格中键入:=Min(A1,B1,C1)其中A1 = a1在我的例子中,B2 = a2在我的例子中,等等,如果我在C1中输入Null,则为min函数等于a1没有问题。

但是,当我尝试在中执行相同的操作时,只要myArray中的元素为空,minvalue就会保持等于0。

我还考虑过尝试用循环手动确定最小值,但它非常难看,我希望尽可能保持代码清洁。

提前感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

这使用循环,但我会考虑这个相当干净的代码。

Sub test()

    Dim a(1 To 3) As Double
    Dim b(1 To 3) As Double
    Dim check(1 To 3) As Boolean
    Dim lowestIndex As Integer
    Dim lowestValue As Double

    Dim i As Integer
    Dim j As Integer

    a(1) = 0.5
    a(2) = 0.6
    a(3) = 0.2

    b(1) = 0
    b(2) = 10
    b(3) = 100


    'initialize to  everything initially
    For i = 1 To UBound(a)
        If (b(i) >= 100) Then
            check(i) = False
        Else
            check(i) = True
        End If
    Next i


    Dim numbTimesToDoStuff As Integer
    numbTimesToDoStuff = 100

    'go through this process however many times you need
    For i = 1 To numbTimesToDoStuff
        'reset each iteration
        lowestValue = 99999

        'find minimum value and index each time
        For j = 1 To UBound(a)
            If (check(j) = True) Then
                If (a(i) < lowestValue) Then
                    lowestValue = a(i)
                    lowestIndex = i
                End If
            End If

        Next j

        'check if no values were found to be lowest and valid
        If (lowestValue = 99999) Then
            MsgBox ("Error: not checking any values!")
        End If

        'update appropriate "b"
        b(lowestIndex) = b(lowestIndex) + 1
        'check if you've reached 100 and stop future checks
        If (b(lowestIndex >= 100)) Then
            check(lowestIndex) = False
        End If


    Next i



End Sub

答案 1 :(得分:2)

您可以使用Filter删除数组中的值。

在这种情况下,Filter用于从数组中删除100值,然后EVALUATE用于获取剩余数组的最小值

Sub Test2()
Dim MyArray()
MyArray = Array(900, 112, 100, 122, 196)
MsgBox Evaluate("Min(" & Join(Filter(MyArray, 100, False), ",") & ")")
End Sub