[英]VB Code not working in excel
Hello I'm trying to get an answer to a pretty basic question but I'm trying to make it work in excel I need the program to display the correct answer on screen at the moment it keeps coming up with 2 my code is 您好,我试图得到一个非常基本的问题的答案,但是我试图使其在excel中工作,我需要程序在不断出现2的时候在屏幕上显示正确的答案,我的代码是
Private Sub CommandButton1_Click()
Dim i As Integer
Dim A1 As Integer
Dim A2 As Integer
Dim Ans As Integer
i = 1
A1 = 31.2928
A2 = 22.352
If (((A1 * i) / 2)) > (A2 * i) Then
Ans = i
Else
i = i + 1
End If
Ans = i
MsgBox "Value is" & Ans
End Sub
I want it to come up with the correct answer to the above statement I want the program to times A1 by i and then divide it by 2 and then see if its bigger than A2 times i and loop around the program until a number is found 我希望它为上述陈述提供正确的答案,我希望程序将A1乘以i,然后除以2,然后查看其是否大于A2乘以i,然后在程序中循环直到找到一个数字
You first set A1
to 31 and A2
to 22. You then calculate (((31 * 1) / 2)) > (22 * 1)
which equates to False
. 首先将
A1
设置为31,将A2
为22。然后计算(((31 * 1) / 2)) > (22 * 1)
,它等于False
。 (It would do so even if you calculated (((31.2928 * 1) / 2)) > (22.352 * 1)
.) Because it is False
you set i
to be i + 1
which is 2
. (即使您计算了
(((31.2928 * 1) / 2)) > (22.352 * 1)
。)因为它是False
,所以将i
设置为2
i + 1
。 You then set Ans = i
, so Ans
is now 2. 然后设置
Ans = i
,因此Ans
现在为2。
I believe what you want is 我相信你想要的是
Private Sub CommandButton1_Click()
Dim i As Integer
Dim A1 As Double
Dim A2 As Double
Dim Ans As Integer
i = 1
A1 = 31.2928
A2 = 22.352
Do
If (((A1 * i) / 2)) > (A2 * i) Then
Ans = i
Exit Do
End If
i = i + 1
Loop
MsgBox "Value is " & Ans
End Sub
However, because 31.2928 * i /2
will never exceed 22.352 * i
(because 15.6464 < 22.352), I would recommend you don't run that code because it will crash out once i
reaches 32767 and gives an overflow error. 但是,因为
31.2928 * i /2
永远不会超过22.352 * i
(因为15.6464 <22.352),所以我建议您不要运行该代码,因为一旦i
达到32767并给出溢出错误,它就会崩溃。
Note: An equation of the form (a * i) > (b * i)
is equivalent to a > b
(after dividing both sides by the common value i
) so the answer will be True
or False
irrespective of the value of i
(assuming positive values of i
) . 注:形式的公式
(a * i) > (b * i)
相当于a > b
(后由公共值除以两侧i
),因此答案将是True
或False
的值无关i
(假设i
正值 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.