Logo

Visual Basic Operators

 

Operators and Operands

 

Introduction

An operation is an action performed on one or more values either to modify one value or to produce a new value by combining existing value. Therefore, an operation is performed using at least one symbol and one value. The symbol used in an operation is called an operator. A variable or a value involved in an operation is called an operand.

A unary operator is an operator that performs its operation on only one operand.

An operator is referred to as binary if it operates on two operands.

The Assignment Operator =

The assignment operation is used to make a copy of a value, a variable, or the content of a control and give the copy to another variable. The assignment operation is performed with the = sign.

After you have declared a variable, before using it, it must have a value. One way you can give a value to a variable is to assign one. For example, if you had declared a variable named NumberOfTracks. You an store a number like 16 in that variable by assigning it the value. You would type NumberOfTracks = 16 as in the following: 

Private Sub Form_Load()
    Dim NumberOfTracks As Integer
    NumberOfTracks = 16
End Sub

When the assignment operator is provided to a variable as a starting value for the variable, this is referred to as initializing the variable.

You can also assign a variable to another as in Variable1 = Variable2. Using this approach, the item on the left side of the assignment operator must be variable and never a (constant) number.

 

Unary Operators: The Positive Operator +

Algebra uses a type of ruler to classify numbers. This ruler has a middle position of zero. The numbers on the left side of the 0 are referred to as negative while the numbers on the right side of the rulers are considered positive:

-∞   -6 -5 -4 -3 -2 -1   1 2 3 4 5 6   +∞
   0
-∞   -6 -5 -4 -3 -2 -1   1 2 3 4 5 6   +∞

A value on the right side of 0 is considered positive. To express that a number is positive, you can write a + sign on its left. Examples are +4, +228, +90335. In this case the + symbol is called a unary operator because it acts on only one operand.

The positive unary operator, when used, must be positioned on the left side of its operand, never on the right side.

As a mathematical convention, when a value is positive, you don't need to express it with the + operator. Just writing the number without any symbol signifies that the number is positive. Therefore, the numbers +4, +228, and +90335 can be, and are better, expressed as 4, 228, 90335. Because the value does not display a sign, it is referred as unsigned.

 

Practical Learning: Using Operators

  1. Start Microsoft Visual Basic and, on the opening dialog box, double-click Standard EXE
  2. To save the project, on the main menu, click File -> Save Project
  3. Locate your MS Visual Basic folder created in the first lesson and display it in the Save In combo box
  4. Click the Create New Folder button. Type Operations and press Enter twice to display it in the Save In combo box
  5. Click Save twice to save the form and the project
  6. Using the controls on the Toolbox, design the form as follows:
     
    Control Caption Name
    Label Number  
    TextBox   txtOperand
    CommandButton Operation cmdOperation
  7. Double-click the Operation button and implement its event as follows:
     
    Private Sub cmdOperation_Click()
        txtOperand = +248.64
    End Sub
  8. Press F5 to test the application
  9. After using it, close the form

Unary Operators: The Negative Operator -

As you can see on the above ruler, in order to express any number on the left side of 0, it must be appended with a sign, namely the - symbol. Examples are -12, -448, -32706. A value accompanied by - is referred to as negative.

The - sign must be typed on the left side of the number it is used to negate.

Remember that if a number does not have a sign, it is considered positive. Therefore, whenever a number is negative, it MUST have a - sign. In the same way, if you want to change a value from positive to negative, you can just add a - sign to its left.

 

Practical Learning: Using The Negative Operator

  1. Change the code of the form as follows:
     
    Private Sub cmdOperation_Click()
        txtOperand = -972.405
    End Sub
  2. Press F5 to test the application
  3. After using it, close the form

Arithmetic Operators

 

The Addition +

The addition is performed with the + sign. It is used to add one value to another.
To add two numbers, such as 225 and 64, you could use 225 + 64. The result would be 289.

The addition is also used to add the values of two variables. For example, you could use CDbl(txtMondayHours) + CDbl(txtTuesdayHours) to get a total number of hours worked on Monday and Tuesday. The result could be stored in another control.

Practical Learning: Using the Addition Operator

  1. Change the design of the form as follows:
      
    Control Caption Name
    Label First Name:  
    TextBox   txtOperand1
    Label Last Name:  
    TextBox   txtOperand2
    CommandButton Addition cmdAddition
    Label Result:  
    TextBox   txtResult
  2. Double-click the Addition button and change its code as follows:
     
    Private Sub cmdAddition_Click()
        Dim dblOperand1 As String
        Dim dblOperand2 As String
        Dim dblResult   As String
        
        dblOperand1 = txtOperand1
        dblOperand2 = txtOperand2
        dblResult = dblOperand1 + " " + dblOperand2
        
        txtResult = dblResult
    End Sub
  3. Test the application. Enter a name one the First Name text box and another name in the Last Name text box then click Addition
     
  4. After using the form, close it

The Subtraction - 

The subtraction operation is performed using the - sign. This operation produces the difference of two or more numbers. It could also be used to display a number as a negative value. To subtract 28 from 65, you express this with 65-28.

The subtraction can also be used to subtract the values of two values.

 

Practical Learning: Using the Subtraction Operator

  1. Change the design of the form as follows:
      
    Control Caption Name
    Label Number 1:  
    TextBox   txtOperand1
    Label Number 2:  
    TextBox   txtOperand2
    CommandButton Addition cmdAddition
    CommandButton Subtraction cmdSubtraction
    Label Result:  
    TextBox   txtResult
  2. Double-click the Addition button and change its code as follows:
     
    Private Sub cmdSubtration_Click()
        Dim dblOperand1 As Double
        Dim dblOperand2 As Double
        Dim dblResult   As Double
        
        dblOperand1 = txtOperand1
        dblOperand2 = txtOperand2
        dblResult = dblOperand1 - dblOperand2
        
        txtResult = dblResult
    End Sub
  3. Test the application. Enter a number one the Number text box and another number in the Number text box then click Subtraction
     
  4. After using the form, close it

The Multiplication *

The multiplication operation allows you to add a number to itself a certain number of times set by another number. The multiplication operation is performed using the * sign. For example, to add 25 to itself 3 times, you would perform the operation as 25 * 3

 

Practical Learning: Using the Multiplication Operator

  1. Add a new CommandButton to the right of the Subtraction button
  2. Change its Name to cmdMultiplication and its Caption to Multiplication
     
  3. Double-click the Multiplication button and change its code as follows:
     
    Private Sub cmdSubtration_Click()
        Dim dblOperand1 As Double
        Dim dblOperand2 As Double
        Dim dblResult   As Double
        
        dblOperand1 = txtOperand1
        dblOperand2 = txtOperand2
        dblResult = dblOperand1 * dblOperand2
        
        txtResult = dblResult
    End Sub
  4. Test the application. Enter a number one the Number text box and another number in the Number text box then click Multiplication
     
  5. After using the form, close it

The Integer Division: \

Dividing an item means cutting it in pieces or fractions of a set value. Therefore, the division is used to get the fraction of one number in terms of another. Microsoft Visual Basic provides two types of operations for the division. If you want the result of the operation to be a natural number, called an integer, use the backlash operator "\" as the divisor. The formula to use is:

Value1 \ Value2

This operation can be performed on two types of valid numbers, with or without decimal parts. After the operation, the result would be a natural number.

 

Practical Learning: Using the Integer Division

  1. Add a new CommandButton to the right of the Subtraction button
  2. Change its Name to cmdDivision and its Caption to Division
     
  3. Double-click the Division button and change its code as follows:
     
    Private Sub cmdSubtration_Click()
        Dim dblOperand1 As Double
        Dim dblOperand2 As Double
        Dim dblResult   As Double
        
        dblOperand1 = txtOperand1
        dblOperand2 = txtOperand2
        dblResult = dblOperand1 \ dblOperand2
        
        txtResult = dblResult
    End Sub
  4. Test the application. Enter a number one the Number text box and another number in the Number text box then click Division
     
  5. After using the form, close it
 

The Decimal Division: /

The second type of division results in a decimal number. It is performed with the forward slash "/". Its formula is:

Value1 / Value2

After the operation is performed, the result is a decimal number. 

 

Practical Learning: Using the Decimal Division

  1. Change the code of the Division button as follows:
     
    Private Sub cmdSubtration_Click()
        Dim dblOperand1 As Double
        Dim dblOperand2 As Double
        Dim dblResult   As Double
        
        dblOperand1 = txtOperand1
        dblOperand2 = txtOperand2
        dblResult = dblOperand1 / dblOperand2
        
        txtResult = dblResult
    End Sub
  2. Test the application. Enter a number one the Number text box and another number in the Number text box then click Division
     
  3. After using the form, close it
  4. Save all
 

The Exponentiation: ^

Exponentiation is the ability to raise a number to the power of another number. This operation is performed using the ^ operator (Shift + 6). It uses the following formula:

yx

In Microsoft Visual Basic, this formula is written as:

y^x

and means the same thing. Either or both y and x can be values, variables, or expressions, but they must carry valid values that can be evaluated. When the operation is performed, the value of y is raised to the power of x. 

 

Practical Learning: Using the Exponent Operator

  1. To start a new application, on the main menu, click File -> New Project...
  2. In the New Project dialog box, double-click Standard EXE
  3. To save the project, on the main menu, click File -> Save Project
  4. Click the Create New Folder button. Type Exponentiation and press Enter twice to display it in the Save In combo box
  5. Click Save twice to save the form and the project
  6. Using the controls on the Toolbox, design the form as follows:
     
    Control Caption Name
    Label This number:  
    TextBox   txtNumber
    Label to the power of  
    TextBox   txtPower
    CommandButton is cmdCalculate
    TextBox   txtResult
  7. Double-click the is button and implement its event as follows:
     
    Option Explicit
    
    Private Sub cmdCalculate_Click()
        Dim dblNumber As Double
        Dim dblPower As Double
        Dim dblResult As Double
        
        dblNumber = txtNumber
        dblPower = txtPower
        dblResult = dblNumber ^ dblPower
        
        txtResult = dblResult
    End Sub
  8. Press F5 to test the application. Enter two numbers in the left two text boxes and click the is button
     
  9. After using it, close the form

 

The Remainder Operator: Mod

The division operation gives a result of a number with or without decimal values, which is fine in some circumstances. Sometimes you will want to get the value remaining after a division renders a natural result.

The remainder operation is performed with keyword Mod. Its formula is:

Value1 Mod Value2

The result of the operation can be used as you see fit or you can display it in a control or be involved in another operation or expression.

 

Visual Basic Operators

 

Comments

In the programming world, a comment is a piece of text in Visual Basic code that Visual Basic (in reality the compiler) would not consider when reading your code. As such a comment can be written any way you want.

In Visual Basic, the line that contains a comment can start with a single quote. Here is an example:

Private Sub Form_Load()
    ' This line will not be considered as part of the code
End Sub

Alternatively, you can start a comment with the Rem keyword. Anything on the right side of rem, Rem, or REM would not be read. Here is an example:

Private Sub Form_Load()
    ' This line will not be considered as part of the code
    Rem I can write anything I want on this line
End Sub

Comments are very useful and you are strongly suggested to use comments regularly. They can never hurt your code and they don't increase the size of your application. Comments can help you and other people who read your code to figure out what a particular section of code is used for, which can be helpful when you re-visit your code after months or years of not seeing it.

 

The Double Quotes: ""

A string is an empty space, a character, or a group of characters that you type or provide to a control and you want this character or this group of characters to be considered "as is". In other words, the expression or the control that receives the string should keep it or them the way you supplied it or them unless you give other instructions regarding the string.

A string can be an empty space or one character, such as $ or w; a group of characters, like home or Manchester United or Verbally speaking, I meanů Ah forget it. Most of the time, you will want the program to keep this character or group of characters exactly the way you or the user supplied them. In order to let the program know that this is a string, you must enclose it in double quotes. From our examples, our strings would be "$", "w", "home", "Manchester United", and "Verbally speaking, I meanů Ah forget it".

To assign a string to an expression or a field, use the assignment operator as follows:

Team = "Manchester United"

In the same way, to initialize a variable with a string , use the assignment operator. Here is an example:

Private Sub Form_Load()
    Dim Address As String
    Address = "12404 Lockwood Drive Apt D4"
End Sub
 

The String Concatenator: &

The & operator is used to append two strings, the contents of two controls, or expressions. This is considered as concatenating them. For example, it could allow you to concatenate a first name and a last name, producing a full name.

The general syntax of the concatenation operator is:

Value1 & Value2

To display a concatenated expression, use the assignment operator on the field. To assign a concatenated expression to a variable, use the assignment operator the same way:

Private Sub Form_Load()
    Dim FirstName, LastName As String
    Dim FullName As String
    
    FirstName = "Francis "
    LastName = "Pottelson"
    FullName = FirstName & LastName
    Text0 = FullName
End Sub

To concatenate more than two expressions, you can use as many & operators between any two strings or expressions as necessary. After concatenating the expressions or values, you can assign the result to another variable or expression using the assignment operator.

 

The Parentheses Operators: ()

Parentheses are used in two main circumstances: in an event (or procedures, as we will learn) or in an operation. The parentheses in an operation help to create sections in an operation. This regularly occurs when more than one operators are used in an operation.

Consider the following operation: 8 + 3 * 5

The result of this operation depends on whether you want to add 8 to 3 then multiply the result by 5 or you want to multiply 3 by 5 and then add the result to 8. Parentheses allow you to specify which operation should be performed first in a multi-operator operation. In our example, if you want to add 8 to 3 first and use the result to multiply it by 5, you would write (8 + 3) * 5. This would produce 55. On the other hand, if you want to multiply 3 by 5 first then add the result to 8, you would write 8 + (3 * 5). This would produce 23.

As you can see, results are different when parentheses are used on an operation that involves various operators. This concept is based on a theory called operator precedence. This theory manages which operation would execute before which one; but parentheses allow you to completely control the sequence of these operations.

 

The Line Continuation Operator: _

You will sometimes need to expand your code on more than two lines. This happens regularly if you are writing an expression that involves many entities that must belong to a group.

To continue a piece of code from one line to the next, type an empty space followed by an underscore symbol, then continue your code on the next line.

 

The Period Operator: .

To access the property of an object, type the name of the object, followed by a period, followed by the name of the property you need. The property you are trying to use must be part of the properties of the object.

If you know the name of the property, you can start typing it. Once the desired property is highlighted, press the Space bar or Tab. If you see the name of the property in the list, you can double-click click it. If the list doesn't appear, press Ctrl + Space bar. If you don't want to use the list displayed by the Code Editor, press Esc. Once you have specified what property you want to use, you can assign it the desired value or you can involve it in any operation you see fit.

 

Previous Copyright © 2001-2005 FunctionX, Inc. Next