2014-12-13 156 views
3

我試圖找到3個輸入的最大值。問題不在算法中,因爲當我在python中創建相同的腳本時,它工作得很好。問題是它不能按預期工作。我會寫一些情景和結局怎樣爲:查找3個輸入的最大值VBA

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

它似乎它適用於q請結合一些組合,但不適合每個人。我還沒有設法找到一個模式,我不知道什麼是錯的。

我附上代碼:

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 
+1

注意,聲明變量爲'點心的x,y和z如Single'將宣佈'x','y'如'Variant'和只有'z'作爲'Single' – 2014-12-13 21:53:09

回答

5

因爲他們使用的InputBox輸入,它是比較文本值。所以,例如「8」大於「12」。相反,嘗試轉換爲Longs像:

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

您還可以簡化您的代碼:

MsgBox WorksheetFunction.Max(x, y, z) 
+0

謝謝。我也注意到使用CSng更好,因爲它也可以使用小數位! – SiGm4 2014-12-13 15:37:21

+0

的確如此。或者'CDbl'如果你想狂野:)。 – 2014-12-13 15:41:19

1

這裏是你要找的模式。

由於X和Y變異,而Z是單身,這是VBA將如何執行的比較:

X VS Y:字符串VS字符串(這是什麼原因造成的所有麻煩)

X VS Z:數字(X將被自動轉換)

ÿVS Z:數字(Y將被自動轉換)

重新評估的你的場景的所有9,其中X和Y被比較字符串和( X或Y)與Z作爲數字進行比較。你觀察到的結果雖然出乎意料,但是是正確的。

只是感到幸運的是,你不是在PHP編程,這是更糟!

如果沒有指定其他類型,Microsoft將責備允許Variant成爲默認數據類型。他們支持「Option Explicit」來強制聲明變量。他們應該更進一步,並且可以選擇在所有聲明中要求數據類型。

+0

哈哈我只是重讀這篇文章,我覺得有必要提到我現在在PHP編程:P – SiGm4 2015-12-30 15:27:04

0

Here是返回它們當中任意數量的最大元素的函數:

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