查找最多3个inputVBA

我试图find最多3个input。 问题不在于algorithm,因为当我在python中创build相同的脚本时,它工作得很好。 问题是,它不能按预期工作。 我会写一些场景,结果是:

8 5 12 – 最大:12
5 8 12 – 最大:12
12 5 8 – 最大:8
12 8 5 – 最大:8
5 12 8 – 最大:8
8 12 5 – 最大:8
100 22 33 – 最大:33
22 3 100 – 最大:100
100 22 3 – 最大:22

它似乎适用于相当多的组合,但不适用于每一个组合。 我还没有设法find一个模式,我不知道什么是错的。

我附上代码:

Sub Maxthree() 'Calculates the maximum of three numbers' Dim x, y, z As Single x = InputBox("Enter the first number!") y = InputBox("Enter the second number!") z = InputBox("Enter the third number!") MsgBox ("X: " & x & " Y: " & y & " Z: " & z) If x > y Then If x > z Then MsgBox ("the maximum is : " & x) Else MsgBox ("the maximum is : " & z) End If Else If y > z Then MsgBox ("the maximum is : " & y) Else MsgBox ("the maximum is : " & z) End If End If End Sub 

因为它们是使用InputBoxinput的,所以它比较文本值。 所以,例如“8”大于“12”。 而是尝试转换为Longs像:

 x = CLng(InputBox("Enter the first number!")) 

你也可以简化你的代码来:

 MsgBox WorksheetFunction.Max(x, y, z) 

这是你正在寻找的模式。

由于X和Y是Variant而Z是Single,这就是VBA如何执行比较:

X vs Y:string与string(这是什么造成了所有的麻烦)

X与Z:数字(X将自动转换)

Y vs Z:数字(Y会自动转换)

重新评估所有9个场景,将X和Y作为string进行比较,将(X或Y)与Z作为数字进行比较。 你观察到的结果虽然出乎意料,但却是正确的。

只是感到幸运的是,你不是在PHP编程,这是更糟的!

如果没有指定其他types的话,微软应该责怪Variant是默认的数据types。 他们支持“Option Explicit”来强制声明variables。 他们应该更进一步,并且可以select在所有声明中要求数据types。

这是一个返回任意数量的最大元素的函数:

 Function Largest(ParamArray a() As Variant) As Variant 'returns the largest element of list 'List is supposed to be consistent: all nummbers or all strings 'eg: largest(2,6,-9,7,3) -> 7 ' largest("d", "z", "c", "x") -> "z" 'by Patrick Honorez --- www.idevlop.com Dim result As Variant Dim i As Integer result = Null For i = LBound(a) To UBound(a) If result > a(i) Then 'nothing to do. This construct will properly handle null values Else result = a(i) End If Next i Largest = result End Function