Excel 查找最多3个输入VBA
我试图找到最多3个输入。问题不在于算法,因为当我用python编写相同的脚本时,它工作得很好。问题是它没有像预期的那样工作。我将写一些场景和结果: 8 5 12-最大值:12Excel 查找最多3个输入VBA,excel,vba,max,Excel,Vba,Max,我试图找到最多3个输入。问题不在于算法,因为当我用python编写相同的脚本时,它工作得很好。问题是它没有像预期的那样工作。我将写一些场景和结果: 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 似乎它对相当多的组合都有效,但不是对每个组合都有效。我还没有找到一个模式,也不知道出了什么问
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
似乎它对相当多的组合都有效,但不是对每个组合都有效。我还没有找到一个模式,也不知道出了什么问题 我附上代码:
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
因为它们是使用InputBox输入的,所以它比较文本值。因此,例如“8”大于“12”。相反,请尝试转换为
Longs
,如:
x = CLng(InputBox("Enter the first number!"))
您还可以将代码简化为:
MsgBox WorksheetFunction.Max(x, y, z)
这是你要找的图案 由于X和Y是变量,而Z是单个变量,因此VBA将执行以下比较: X vs Y:string vs string(这就是造成所有问题的原因) X对Z:数字(X将自动转换) Y vs Z:数字(Y将自动转换) 重新评估所有9个场景,将X和Y作为字符串进行比较,将(X或Y)与Z作为数字进行比较。您观察到的结果虽然出乎意料,但却是正确的 幸运的是,你没有用PHP编程,而这一切更糟糕 如果未指定其他类型,则Microsoft应负责将Variant作为默认数据类型。它们支持“optionexplicit”来强制声明变量。它们应该更进一步,并且可以选择在所有声明中要求数据类型。是一个返回任意数量声明中最大元素的函数:
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
'e.g: 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
非常感谢。我还注意到使用CSng更好,因为它也可以使用小数!没错。或者
CDbl
如果你想变得疯狂:)。注意,将变量声明为Dim x,y,z为Single
将声明x
,y
为Variant
并且仅z
为Single
哈哈,我刚刚重新阅读了这篇文章,我觉得有必要提到我现在正在用PHP编程:P