Search code examples
excelvbauserform

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?


Solution

  • 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