Reputation: 11
I'm doing a simple program in Excel VBA. I have created a simple UserForm for arithmetic operations. I have created two input text boxes and 4 command boxes for addition, subtraction, multiplication and division. When I run the code I am able to do all operations except addition operation. When I enter the two inputs and click on addition command button, the result is getting concatenated instead of doing the addition operation. Eg: Input 1 = 10 , Input 2 = 10. Result= 1010.
Here is my code:
Private Sub CommandButton2_Click()
ANSWER = INPUT1 * INPUT2
End Sub
Private Sub CommandButton3_Click()
ANSWER = INPUT1 - INPUT2
End Sub
Private Sub CommandButton4_Click()
ANSWER = INPUT1 + INPUT2
End Sub
Private Sub CommandButton5_Click()
ANSWER = INPUT1 / INPUT2
End Sub
Here is the image of the ouput i am getting for the addition operation
Upvotes: 1
Views: 1986
Reputation: 2725
Two things to look at here:
Anything typed into a text box is a string, such that MsgBox TypeName(me.Textbox1)
will always gives:
"+
" will be a concatenation operator when both variables are strings.
Hence you will have to explicitly convert the variables into numbers before using the +
to add them so that the +
will not be treated as a concatenation operator.
To convert text to numbers, you can use Val
, CDbl
, CInt
, CLng
or CSng
. Choose the best fit.
Upvotes: 1
Reputation: 22876
You can also use -*\/
to convert the the text to number:
ANSWER = INPUT1 - 0 + INPUT2
ANSWER = INPUT1 * 1 + INPUT2
ANSWER = INPUT1 / 1 + INPUT2
ANSWER = INPUT1 \ 1 + INPUT2 ' integer division
ANSWER = INPUT1 + --INPUT2
ANSWER = INPUT1 - -INPUT2
Upvotes: -1
Reputation: 520
Try changing the code to force numeric operations.
ANSWER = Val(INPUT1) + Val(INPUT2)
You might want to put a check in there.
If IsNumeric(Input1) Then
INPUT1 = Val(INPUT1)
Else
INPUT1 = 0
End if
Something like that for each variable you are using.
Upvotes: 1