Inside Man
Inside Man

Reputation: 4293

How to sum two numbers using a Userform and output it in a MsgBox?

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:

Private Sub TextBox1_Change()
Dim a As Integer
a = Val(TextBox1.Text)
End Sub

and this for 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?

Upvotes: 1

Views: 39313

Answers (4)

Amith Gouda
Amith Gouda

Reputation: 11

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

Upvotes: 0

Gowtham
Gowtham

Reputation: 11

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

Upvotes: 1

Macklein reyes
Macklein reyes

Reputation: 11

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

Upvotes: 1

Gaijinhunter
Gaijinhunter

Reputation: 14685

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.

Private Sub CommandButton1_Click()

MsgBox(TextBox1.Value + TextBox2.Value)

End Sub

Upvotes: 3

Related Questions