VBA for Excel 2007 tutorial-VBA Operators


VBA Operators

When you have variables declare, you may need to do some operations with them or you can use them to store values for use later in your  program. Therefore you need to know VBA operators that can be use to do such things.

To run the VBA example code, you may need to create a new form by using VBA Editor. Then add one command button as you will click the button to show the result. The group of tools(including command button) is display when you click the Toolbox in the ribbon.


VBA for Excel: Toolbox

VBA for Excel--Create a form


-Assignment Operators(=) is used to assign value to variable.

Example:
Dim x As Integer
x=10
 
-Arithmetic operators (+,-,*, /, mod) are used to do math operations such as addition, subtraction, multiplication, division, and modulus of division.

Example:
Dim x As Integer
Dim y As Integer
Dim sum As Integer
 
x=10
y=20
sum=x+y
Msgbox “Total=” & sum
 
-Logical operators (And, Or, Xor , Not) are used to do logical operations such and, or, exclusive or, and not.

0=false, 1=true
 

left Value

Operator

Right value

Result

0

And

0

0

0

And

1

0

1

And

0

0

1

And

1

1

0

Or

0

0

0

Or

1

1

1

Or

0

1

1

Or

1

1

0

Xor

0

0

0

Xor

1

1

1

Xor

0

1

1

Xor

1

0

 
-String concatenation operator (&) is used to concatenate sub strings.
Example:
Msgbox “Lastname: “ & “Yuk”
 
-Line feed operator (Vbcrlf) is used to make a new line in the text output.
Example:
Msgbox “Lastname:”& “Yuk” & Vbcrlf & “Firstname:” &”Dara”
 
-Underscore operator(_) is used to continue code when it is too long to write it on a single line.
Example:
Sub_
 printval
End Sub
 
-Comparison operators (=,>,<,>=,<=,<>) are used to compare values. The results from using comparison operators are true or false.
Example:
Dim f As Boolean
f=10>5
Msgbox f
 
-Comma operator (,) is used to separate variables declared.
Example:
Dim x,y,sum As Integer


Comments





This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.