从列表或数组中找出排除某些元素的最小值

  • 我有一个variables列表,我需要find的最小值和评估作为候选人增加一个不同的,相关的值。
  • 然而,已经等于100(以百分比表示)的variables不应该被考虑,因为它们不能超过100。

(确定variables是a,增量值是b's)

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 

我希望代码注意,尽pipea3是最小值,但是b3不能再增加,所以下一个最小值是a1,因此b1增加1。

这个function可以在常规的Excel电子表格中工作。 我可以创build一个值列表,然后在下面的单元格中键入: =Min(A1,B1,C1)其中A1 = a1在我的示例中,B2 = a2在上面的示例中,等等,如果我键入Null C1,min函数等于a1没有问题。

然而,当我尝试在vba中做同样的事情时,只要myArray中的元素为Null,minvalue就等于0。

我也研究过试图手动确定循环的最小值,但这是非常丑陋的,我想保持尽可能干净的代码。

在此先感谢您的帮助。

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

 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 

您可以使用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