vba 如何使用用户表单对两个数字求和并将其输出到 MsgBox 中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10780939/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to sum two numbers using a Userform and output it in a MsgBox?
提问by Inside Man
I have created a userform with three textboxes.
我创建了一个包含三个文本框的用户表单。
The first textbox is for the first number, the second for entering the second number, and the last one is the result.
第一个文本框用于输入第一个数字,第二个用于输入第二个数字,最后一个是结果。
I have create a button named Calculate.
我创建了一个名为计算的按钮。
I have this code for textbox1:
我有 textbox1 的代码:
Private Sub TextBox1_Change()
Dim a As Integer
a = Val(TextBox1.Text)
End Sub
and this for textbox2:
这对于 textbox2:
Private Sub TextBox2_Change()
Dim b As Integer
b = Val(TextBox2.Text)
End Sub
and I have a button which shows the result
我有一个显示结果的按钮
Private Sub CommandButton1_Click()
Dim c As Integer
c = a + b
MsgBox (c)
End Sub
I enter 1 for textbox1 and 2 for textbox2, 1+2 will be 3, but in the MsgBox I see 0. Why is this, and how can I fix it?
我为 textbox1 输入 1,为 textbox2 输入 2,1+2 将是 3,但在 MsgBox 中我看到 0。这是为什么,我该如何解决?
回答by aevanko
I wouldn't assign the values of the boxes to variables (and unless they are global variables, the scope of the variables life is the routine, so the variable will die after the sub() for each is over, so when the command button event occurs, the variables are no longer alive), just reference them directly. Just add this for your command button and it should do the job.
我不会将框的值分配给变量(除非它们是全局变量,否则变量生命的范围是例程,因此变量将在每个 sub() 结束后死亡,因此当命令按钮事件发生,变量不再存在),直接引用它们。只需为您的命令按钮添加它,它就可以完成这项工作。
Private Sub CommandButton1_Click()
MsgBox(TextBox1.Value + TextBox2.Value)
End Sub
回答by Macklein reyes
declaration of variables must be in general, it shouldn't be under the Sub...
变量的声明必须是一般的,它不应该在子......
Dim a As Integer
Dim c As Double
Dim b As Integer
Private Sub CommandButton1_Click()
c = a + b
MsgBox (c)
End Sub
Private Sub TextBox1_Change()
a = Val(TextBox1.Text)
End Sub
Private Sub TextBox2_Change()
b = Val(TextBox2.Text)
End Sub
回答by Gowtham
Private Sub Calculate_Click()
Dim a As Integer
Dim b As Integer
Dim c As Integer
a = Val(`TextBox1.Text`)
b = Val(`TextBox2.Text`)
c = a + b
MsgBox (c)
End Sub
回答by Amith Gouda
Dim a As Double
Dim b As Double
Dim c As Double
Private Sub CommandButton1_Click()
a = Val(TextBox1.Text)
b = Val(TextBox2.Text)
c = a + b
MsgBox (c)
End Sub