+ Operator Example
This example uses the + operator to sum numbers. The + operator can also be used to concatenate strings. However, to eliminate ambiguity, you should use the & operator instead. If the components of an expression created with the + operator include both strings and numerics, the arithmetic result is assigned. If the components are exclusively strings, the strings are concatenated.
Dim MyNumber, Var1, Var2
MyNumber = 2 + 2 ‘ Returns 4.
MyNumber = 4257.04 + 98112 ‘ Returns 102369.04.
Var1 = “34″: Var2 = 6 ‘ Initialize mixed variables.
MyNumber = Var1 + Var2 ‘ Returns 40.
Var1 = “34″: Var2 = “6″ ‘ Initialize variables with strings.
MyNumber = Var1 + Var2 ‘ Returns “346″ (string concatenation).
The above explanation is about + Operator found in Microsoft Excel VBE help topic. When we use Userform and TextBox in VBA to sum the value for all TextBox we must use variable otherwise it will become String Concatenation meaning joint not add or plus. For example 2 + 2 will become 22 not 4 as total. Let try below example, before try we must add UserForm; add 4 TextBox and 1 button into this UserForm in VBE.
TextBox1 ~ TextBox3 for user to input, TextBox4 total value when we click the Button1
Now Double click the Button1 to insert below code:
Option Explicit Private Sub CommandButton1_Click() Dim iNum(1 To 3) As Double iNum(1) = TextBox1.Value iNum(2) = TextBox2.Value iNum(3) = TextBox3.Value TextBox4.Value = iNum(1) + iNum(2) + iNum(3) End Sub
Now run this code, input any number into TextBox1 to TextBox3 then click Button1. Now you can see the result.What happen if we change your declaration Statement from Dim iNum (1 To 3) As Double to Dim iNum (1 To 3) As String. The answer will be different and this time we will get Concatenation not Addition.
Note: Why we use double instead of integer? If we declare as integer the answer is without decimal and limit to 32k, the chances we get error “Run time error ‘6’ over flow” is high. This is depending on your program needs or purpose.
If you have any question or project please e-mail to me, I will reply and create for free.
Click Here to E-mail
Enjoy your learning.