3
  • 我有一个变量列表,我需要找到它的最小值并评估为候选值,以将不同的相关值增加 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)where A1 = a1 in my example, and B2 = a2 in my above example, etc. 如果我在 C1 中键入 Null,则 min 函数等于 a1 而没有问题。

但是,当我尝试在中做同样的事情时,只要 myArray 中的元素为 Null,minvalue 就会一直等于 0。

我还研究过尝试使用循环手动确定最小值,但它非常难看,我希望尽可能保持代码干净。

在此先感谢您的帮助。

4

2 回答 2

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
于 2012-10-15T19:22:20.503 回答
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
于 2012-10-16T05:34:19.283 回答