• No results found

Microsoft Visual Basic 2010 Tutorial

N/A
N/A
Protected

Academic year: 2021

Share "Microsoft Visual Basic 2010 Tutorial"

Copied!
485
0
0

Loading.... (view fulltext now)

Full text

(1)

Language Fundamentals Introduction to Microsoft Visual Basic 2010 Express Introduction to Projects | Operators and Operands Introduction to Variables | Using Variables Enumerations | Strings

Incrementing/Decrementing Values

Procedures and Functions

Fundamentals Built-In Functions

Introduction to Procedures Arguments and Parameters Introduction to Built-In Functions Static Variables Optional Arguments Overloading a Procedure Conversions Int/Fix Format Number Format Currency Format Percent Len Random Functions Conditional Statements Boolean Values | Logical Operations

Introduction to Conditional Statements Functional Conditions

Conditional Selections

Managing Conditional Statements

Classes

Fundamentals Topics on Classes

Introduction to Classes The Methods of a Class

Class Construction and Destruction Structures

The Shared Members of a Class Characteristics of Members of a Class Nesting a Class

The Properties of a Class Operator Overloading

Inheritance and Abstraction Built-In Classes

Inheritance Polymorphism Class Abstraction

Object Random

(2)

Language Topics Strings

Date and Time Values Message Boxes Input Boxes Delegates Namespaces

Data Reading and Formatting Custom Libraries

Error Handling Events

Exception Handling Introduction to Errors and Debugging

Options on Debugging Error Handling

Introduction to Exceptions .NET Framework Support

File Processing Introduction File Streams Exception Handling Directories Files

(3)

Introduction to Microsoft Visual Studio

MSVB

Introduction

Microsoft Visual Basic is a computer programming environement used to create graphical applications for the Microsoft Windows family of operating systems. It uses a computer language of the same name. Like every computer language, Visual Basic is used to give instructions to a computer. The instructions can be written from a text editor such as Notepad. Another way is to use a programming environment that is equipped with many tools that make it easy to work on projects, to create the necessary files, and to distribute a completed application.

To follow our lessons, you can use Microsoft Visual Studio 2010 or Microsoft Visual Basic 2010 Express. To get Microsoft Visual Basic 2010 Express, get to the Microsoft web site and click the Visual Studio Express link.

Starting Microsoft Visual Basic Express

TTo launch Microsoft Visual Basic 2010 Express, you can click Start -> (All) Programs -> Microsoft Visual Studio 2010 Express -> Microsoft Visual Basic 2010 Express:

To launch Microsoft Visual Studio 2010, you can click Start -> (All) Programs -> Microsoft Visual Studio 2010.

The Microsoft Visual Studio Interface

The Main Menu

The top section of Microsoft Visual Studio displays the main menu divided in categories such as File or Edit. The main menu is used like the menu of a normal application.

The Toolbars

Under the main menu, there is a toolbar. Normally, when the studio is launched, it displays the Standard toolbar as its default. Some additional toolbars will display in response to an action

(4)

from you. Still, you can display other toolbars if you want. To do this:

On the main menu, click View -> Toolbars and click the toolbar of your choice

Right-click the main menu or any toolbar. In the that appears, click the desired toolbar

Toolbars are used in the same they are in other applications.

Microsoft Visual Studio's menus and toolbars can be customized. You can customize a menu category on the main menu by adding a menu item to it. You can customize a toolbar by adding a button to it. To start, right-click anything on the main menu or on any toolbar and click Customize... For example, imagine you want to add an item named Start Without Debugging to the left side of the Start button:

To do this:

a. Right-click the main menu or a toolbar and click Customize b. On the Customize dialog box, click the Commands tab

c. Click the Toolbars radio button

d. In the Toolbars combo box, select the toolbar that will host the button. For our example, that would be Standard

e. In the Controls list, click the button that will come after the new button. For our example, that would be Start / Continue:

(5)

f. Click Add Command...

g. In the Categories list of the Add Command dialog box, select the category that has the button you want. For our example, that would be Debug

h. In the Commands list, click the desired button or menu item. For our example, that would be Start Without Debugging

(6)

j. On the Customize dialog box, click Close:

In the same way, you can customize any toolbar and any menu category.

The Start Page

The Start Page is the main body of Microsoft Visual Studio or Microsoft Visual Basic Express when it has been launched. It starts on top with a tab labeled Start Page. The main body of Microsoft Visual Basic Express displays Microsoft Visual Basic 2010 Express. The left section shows two labels: New Project... and Open Project... When some projects have been previously created or used, their names appear under Open Project... When you work on a project, the Start Page is usually in the background but it is represented by a tab. At any time, to display the Start Page:

You can click the Start Page label in the top section of the Code Editor On the main menu, you can click View -> Start Page

Showing and Closing a Window

When you start or open a project, the studio makes some windows available. These are the most regularly used windows. If you think that one of them is not regularly used in your types of assignments, you can remove it from the screen. To hide a window, you can click its Close button .

All of the windows you can use are listed in the View menu. Therefore, if a window is not displaying, you can click View on the main menu and click a window of your choice.

(7)

Auto Hiding a Window

When working on a project, you will use a set of windows that each accomplishes a specific purpose. Some windows are represented by an icon but hide the rest of the body. To display such a window, you can position the mouse on it. This would expand the window:

If you expand a window, it would display a title bar with three buttons. One of the button is called Auto Hide:

If you expand a window but find out you don't need it any more, you can just move the mouse away. The window would return to its previous state. Based on this functionality, if you are working with a window and move the mouse away, it would retract. If you need it again, you would have to reopen it using the same technique. If you are going to work with a certain window for a while, you can keep it open even if you move the mouse away. To do this, you can click the Auto Hide button. If clicked, the Auto Hide button changes from pointing left to pointing down:

(8)

By default, the studio installs some windows to the left and some others to the right of the screen. You can change this arrangement if you want. To do this, expand a window, then click its title bar and start dragging. While you are dragging, to assist you with a new position, the studio displays five boxes:

Docking a Window to a Side of the Studio

To position a window on one side of the studio, drag its title bar to the box that represents that side. When you get to a side, a transparent blue rectangle would be drawn to indicate the possible position. Drop the window to either the most left guiding box to position it to the left of the screen, or to the most right guiding box to position it to the right of the screen. Here is an example:

(9)

or

To position a window to the top or the bottom side of the studio, drag its title bar to either the most top guiding box to position it to the top of the studio or to the most bottom guiding box to position it to the bottom of the studio. Here is an example:

(10)

Docking a Window Above or Below Another

To make two windows share an area, you can position one above or below an existing window. Of course, you must first have a window as reference. Then, drag the second window to the existing window. Drop it in the

This

(11)

Floating Windows

Most of the windows you will use are positioned on one side of the screen. If you want, you can have a window that stays on top of other windows but is not "glued" to one side. Such a window is said to float. To float a window, drag its title bar and release it somewhere in the middle of the screen but not on a guiding box.

When a window is floating, it displays a Maximize button on the title bar. If you click this button, the window occupies the whole interface of Microsoft Visual Studio. In the same way, if you double-click the title bar, the window gets maximized.

(12)

If a window is currently docked and you want to float it, right-click its title bar and click Float.

Coupling Windows

You can make two or more windows share one side of the screen or to share an area. To do this, first expand and dock the window that you will use as the base (or reference). Then, drag the title bar of the window that will share the area to its target until the bottom part of the base window shows a highlighted and a non highlighted area:

(13)

To remove a window that shares an area, drag its tab away:

To position a window to the left or the right of an existing window, first drag the second window to where the existing window is. Then click the left (or the right, depending on the side you want) guiding box of the multiple-box.

(14)

becomes this

In the same way, you can make two or more windows share the same area.

Tabbed Windows

You can make a window display its tab in the top section of the Code Editor and share the area with it. There are two ways yon do it

You can drag a window and drop it on the tab of the Start Page.

(15)

becomes this

If a window is already represented with a tab on top of the Code Editor, you can drag the second window and drop it to the left or of the right tab of the existing window.

You can right-click Dock as Tabbed Document

(16)

Introduction to Projects

The Visual Basic Language in Microsoft Visual Basic

The Basic

Microsoft Visual Basic is not just a production environment. It also includes a fully functional language that can stand on its own. The language started as Basic, then QuickBasic or QBasic. It first went through various changes. In 2002, Microsoft created a new serious language that can understand and use the .NET Framework. Microsoft Visual Basic is used to create graphical applications, also referred to as Graphical User Interface (GUI) applications, web-based applications, and other types of applications. In order to effectively create these applications, you must be familiar with the language used in this programming environment.

In our lessons, we are going to study the language that serves as a foundation to the Microsoft Visual Basic programming environment.

Introduction to Projects

The primary job of an application is to show its results on the monitor. A console application is one that displays its results in a black window referred to as a DOS window. In some of our lessons, we will create those types of applications. The Visual Basic language provides a rectangular object called a message box. If you create a Visual Basic application, you can display the results in a message box. That's what we will use in most of our lessons.

To create an application, you start with a project. There are two main ways you can create a Visual Basic project. You can use a text editor or a programming environment.

A Program's File

To create a program, you write the necessary instructions in a text-based document. This is called a source file. A source file that contains Visual Basic instructions is a regular, simple, ASCII, text-based file. It has the extension .vb as a Windows file.

Practical Learning: Starting a Project

1. Start Notepad

2. To save the empty document, on the main menu of Notepad, click File -> Save 3. In the top combo box, locate and select the C: drive

4. Click the New Folder button

5. Set the name to Exercise1 and press Enter 6. Display that folder in the top combo box 7. Specify the name of the file as Exercise.vb

(17)

8. Click Save

Introduction to Modules

In Visual Basic source file, you write code as we will learn throughout our lessons. The code that is conform to the Visual Basic language is included in a section known as the module. This section starts with the Module keyword followed by a name and ends with the End Module expression. Everything between the line that has Module and the line that has End Module belongs to the same entity. Based on this, a simple file in Visual Basic would have the following:

Module ModuleName End Module

Practical Learning: Introducing Modules

1. In the empty document, type the following:

Module Exercise End Module

2. On the main menu, click File -> Save

(18)

A procedure is a section of code that takes care of a specific task. In a module, the basic formula of a procedure is:

Sub ProcedureName() End Sub

Notice that it ends with the End Sub line. Because a module holds the code of a Visual Basic program, a procedure is included inside the start and the end of the module section. This would be done as follows: Module ModuleName Sub ProcedureName() End Sub End Module

We will come back to procedures in another lesson. For now, the most fundamental procedure used in Visual Basic is called Main. In a program, the Main procedure is the entry point. That is where the program starts.

Another common procedure highly used in Visual Basic is called MsgBox. As its name indicates, the

MsgBox procedure is used to display a message in a dialog box. To make this happen, you can

include the message inside the parentheses of MsgBox. The message itself should be included in double-quotes. An example would be:

MsgBox("Whatever")

To distinguish a procedure from other items used in a program, we will sometimes write it followed by parentheses. Examples are Main() and MsgBox().

The MsgBox() procedure provides more details. We will come back to it in Lesson 7.

Practical Learning: Introducing Procedures

1. Change the document as follows:

Module Exercise Sub Main()

MsgBox("Welcome to the Wonderful World of Visual Basic.") End Sub

End Module

2. On the main menu, click File -> Save

Building a Program

As mentioned already, you write the instructions of your project in English. But the computer doesn't understant it. The instructions must be translated in a language the computer can understand. That language is called machine language. To translate the instructions from English to machine dialect, you use a program named a compiler. In reality, a compiler is a group of sub-programs that accomplish various goals to get a functional program at the end. The end result is a program that can be executed in a computer other than the one you used to create the project. That final program is called an executable.

Ae mentioned already, a compiler is a computer program made of internal other sub-programs. One of the sub-programs, in fact probably the first, of a compiler is called a parser. A parser "scans" a file that contains (part of) the program. It checks the syntax, keywords, unknown words, and some other routines. If the parser finds a problem, which could be anything, either it stops or it continues making a list of the mistakes it found. Then it displays this list to you to fix. Sometimes it would point to the exact line where the/a problem was found. Sometimes it would point to the line where the problem showed its impact although the problem may be found somewhere else. With experience, you will know how to fix the programs or troubleshoot the problems.

If the parser doesn't find any problem, or after you have fixed the problems, it (the parser) passes its result(s) to the compiler. The compiler calls another program called a linker. If the program contains just one file, the linker considers it. If the program contains more than one file, the linker considers them. The linker gathers some of the files that the compiler shipped with (those files that your program needs in order to work), puts them together ("links" them) with your file(s) to get your instructions in a manner that can produce a suitable result. If there is no significant problem, the compiler creates the executable. This doesn't mean that everything is alright, it only means that the

(19)

compiler thinks that everything is alright: it is still possible that the result may not be what you would expect. We will come back to these issues.

To make your life easier, all of the sub-programs (parser, linker, debugger, etc) that ship with Visual Basic are grouped in one large program: the compiler. Therefore, from now on, we will use the word "compiler" to refer to the program you use to translate your English instructions into a machine language.

Microsoft created and makes freely available a Visual Basic compiler you can use to create your applications. The Visual Basic compiler is named vbc. A compiler is primarily a computer program, that is an executable. As such, it uses to extension .exe. Therefore, the compiler we will use to create our program is called vbc.exe.

As mentioned already, the vbc.exe compiler is freely available. You can get it by downloading the .NET Framework from the Microsoft web site. Normally, you are likely to have the .NET Framework installed in your computer already. By default, it is installed in

C:\Windows\Microsoft.NET\Framework\v4.0.21006.

You can use the vbc.exe to create programs from the Command Prompt. To do this, you can add the compiler's path to the Path of the Environment Variables. To start, use a file utility such as Windows Explorer and display the folder where vbc.exe is installed. Here is its path in Windows Explorer:

Select the path in the top combo box and copy it to the clipboard. Start the Control Panel. Click System and Security:

(20)

In the System and Security section, click System:

In the System window, click Change Settings. In the System Properties dialog box, click the Advanced tab. Click the Environment Variables button:

(21)

In the System Variables section, double-click Path or click it and click Edit:

(22)

Click OK three times.

Open the Command Prompt. Type CD\ and press Enter to move to the root drive. Type CD and a space, followed by the folder (and sub-folder(s)) where the file is located, and press Enter. To compile, type vbc followed by the name of the file and its extension:

The file produced from this operation has the extension .exe. By default, it holds same name as the file you had used. If you want to get an executable using a name of your choice, after vbc, type

/out: followed by the name you want, followed by a .exe extension, followed by a space, and followed

by the name of the file you had created, with its extension. The formula to follow would be:

vbc /out:NameOfExecutate.exe Filename.vb

The NameOfExecutate represents the name you want the executable to have. If the name you want is

in one word, you can just type it. Here is an example:

(23)

If you want a name made of various words, you can include those words in double-quotes.

If you are creating your application using a text editor and if you create many files, when compiling the project, you must remember to reference each file. To do that, in the last section, add the name of each file with its extension:

vbc FileName1.vb FileName2.vb FileName_n.vb

The executable you get is the one you can use on other computers and that you can distribute to other people.

Executing a Program

After building the code, you and your users can execute it. If you are working from the Command Prompt, to execute the project, type the name of the file that has the .exe extension and press Enter:

If you are working from Microsoft Visual C# 2010 Express or from Microsoft Visual Studio, to execute an application, on the main menu, you can click Debug -> Start Debugging.

(24)

Creating a Project

Although you can creat a complete and fully functional application using a text editor, Microsoft Visual Studio and Microsoft Visual Basic 2010 Express provide a graphical environment that is more convenient. You start by creating a project. To create a project:

On the main menu, click File -> New Project... On the Start Page, click New Project...

Press Ctrl + N

Creating a Solution

When you start a new application from the New Project dialog box, you are asked whether you want to create a new solution too, and you must give it a name. By default, the new project and solution would hold the same name. If you accept the suggestions, you would get a main folder with the name of the project. Inside of that folder, there would be a folder with the same name. That inside folder would represent the project.

After creating a solution, its name appears on the title bar of Microsoft Visual Studio. The name of the project would appear in the Solution Explorer.

Practical Learning: Introducing the Visual Basic Language

1. Launch either Microsoft Visual Studio or Microsoft Visual Basic 2010 Express 2. On the main menu, click File -> New Project...

3. If you are using Microsoft Visual Studio, in the left list, expand Visual Basic and click Windows. In the right list, click Empty Project. Change the Name to GeneralCensus before clicking OK

If you are using Microsoft Visual Basic 2010 Express, in the middle list, click Console Application. Change the Name to GeneralCensus

(25)

Click OK

Introduction to Managing Solutions and Projects

The Solution Explorer

The Solution Explorer is a window that displays a list of the files that make up a project. To access the Solution Explorer:

If the Solution Explorer is not yet showing on the screen: On the main menu, click View -> Solution Explorer

On the Standard toolbar, click the Solution Explorer button If the Solution Explorer is already showing, click its tab

The Solution Explorer is made of four sections. Like every regular window, the Solution Explorer is equipped with a title bar that displays its name on the left side and three buttons on the right side:

The Window Position button displays a menu when you click it:

The Float option is enabled if the window is docked to a side of the screen. The Float option is disabled if the window is already floating. If the window is docked and you click Float, it would be moved from its docked position and would float. As an alternative to float a docked window, drag its title bar away from its docked position:

(26)

To dock a floating window, drag its title bar

Under its title bar, the second section of the Solution Explorer is a toolbar: :

The Properties button allows you to display the Properties window The Show All Files button is used to show the hidden files of the project

As its name indicates, the Refresh button is used to refresh the list of files and resources of the project

The View Code button is used to show the code of a class

The third part of the Solution Explorer is its body. It shows the folders, files, and resources that are part of the current project. To expand a node, you can either click its button or double-click its name. To collapse a node, either click its button or double-click it.

The root of the list is the name of the solution. Under the root is the name of the current project. If the solution contains more than one project, the name of each project is represented under the solution. Inside of the project are its folders, files, and resources. The first item under a project name is References. After the References node, there are the names of the classes that are part of the project.

The fourth part of the Solution Explorer is its tab.

The Properties Window

The Properties window shows the Windows operating system's details of the files or resources used in a project. To display it:

If the Properties window is not yet displaying

Oon the main menu, click View -> Properties window On the Standard toolbar, click the Properties button If the Properties window is displaying already, click its tab

The display and rectangular behavior of the Properties window follows the description we had for the Solution Explorer.

To show the operating system's characteristics of a project or a file, in the Solution Explorer, click the object:

If you click a solution, the Properties window would show its name and its location If you click a project, the Properties window would show its project file

If you click a file, the Properties window would show its name (in the File Name field) and its location (in the Full Path) field

The Properties window displays different fields depending on the item selected in the Solution Explorer. You can change some things in the Properties window. When a field is disabled, it means you cannot modify it.

Managing a Solution

Introduction

(27)

A solution is used to coordinate the different aspects of an application that is being created. When you have created a project, the name of the solution displays as the top node of the tree in the Solution Explorer:

The title bar of the studio displays the name of the solution in the left section:

If you start saving a project for the first time, it would bring the Save Project dialog box. By default, Microsoft Visual Studio selects your personal directory as the path to the solution. This is called the location. In the location, Microsoft Visual Studio creates a folder as the solution of the project. The solution must have, or must be stored, in its own folder. As mentioned earlier, Microsoft Visual Studio uses the name of the project as the name of the solution. To rename the solution, you can change the string in the Solution Name text box. Remember that you can enter the name of the project in the Name text box. Here is an example:

When you save a project (for the first time), by default, Microsoft Visual Studio creates a new folder for it in the Documents\Visual Studio 2010\Projects folder. It uses the name of the solution to name the folder. It creates some files and stores them in that new folder. Then, it creates a sub-folder, using the name of the project, inside of the folder of the solution. Besides the sub-folder with the name as the project, it creates another folder named debug. It also creates another folder named Debug in the sub-folder of the name of the project. In each folder and some other folders, it creates some files that we will not pay attention to for now.

If the project had already been saved but you want to change the name of the solution, on the main menu, you can click File -> Save solution-name.sln As... This would bring the Save File As dialog box where you can specify the name of the solution and click Save.

(28)

If you don't like the name of a solution, to rename it, in the Solution Explorer, right-click it and click Rename:

As an alternative, in the Solution Explorer, click the name of the project, in the Properties window, click the value of the (Name) field, then edit it or type a new one:

Deleting a Solution

Deleting a Solution is equivalent to deleting a file. To delete a solution, use a file utility such as Windows Explorer, locate the folder that contains the solution, and delete it.

Managing a Project

Saving a Project

If you are creating your application using a text editor, you must save your file(s) in a folder you will create. When Microsoft Visual Studio 2010 (any edition) is installed, it creates a folder named Visual Studio 2010 in your Documents folder. The Documents folder is called your personal drive or your personal directory. Inside of the Visual Studio 2010 folder, it creates a sub-folder named Projects. By default, this is where it would save your projects, each with its own folder.

(29)

To save a project, on the Standard toolbar, you can click the Save All button . Alternatively, on the main menu, you can click File -> Save All. If the project had already been saved but you want to save it under a different name, on the main menu, you can click File -> Save project name As...

Opening a Project

There are a various ways you can open an existing project: On the main menu, click File -> Open Project...

On the Start Page, click Open Project... Press Ctrl + Shift + O

Adding a Project

A solution in Microsoft Visual Studio can contain one or more projects. That is, after creating the first project, you can add another project to the same solution and you can add as many projects as you want.

To add a new project to a solution (in Microsoft Visual Studio): On the main menu, click File -> Add -> New Project...

In the Solution Explorer, right-click the name of the solution, position the mouse on Add, and click New Project... This would display the Add New Project dialog box. In the Templates list, select the type of project you want. Accept or change the name of the project, then click OK.

The names of the different projects are listed in the Solution Explorer.

Renaming a Project

To rename a project, in the Solution Explorer, right-click its name under the solution and click Rename. Type the new name and press Enter.

Managing the Files of a Project

Adding a File to a Project

As mentioned already, a project can contain many files. If you are using a text editor, you can create and save files continuously as you see fit. If you are using Microsoft Visual C# 2010 Express or Microsoft Visual Studio, to add a new file to a project:

On the main menu, click Project -> Add New Item...

In the Solution Explorer, right-click the name of the project, position the mouse on Add, and click New Item...

This would display the Add New Item dialog box. From there, select the type of file you want. Accept or change its name. Then click Add.

When a project is made of various files, each file is represented by a label in the top section of the Code Editor. Here are examples:

Each file is also represented in the main menu under Windows.

Adding an External File

(30)

import that file. To do this;

On the main menu, click Project -> Add Existing Item...

In the Solution Explorer, right-click the name of the project to which you want to import the file, position the mouse on Add, and click Existing Item...

Any of these actions would display the Add Existing Item dialog box with the name of the project on the title bar. Locate the file, select it, and click Open.

Accessing a File

If you are using a text editor to write your code, you can use that editor to open a file. For example, in Notepad, you can click File -> Open... If you are trying to open a source file, first change the file type combo box to All Files (*). Then locate the file from its folder and click Open.

In Microsoft Visual Studio or Microsoft Visual C# Express, if a file is a member of the current project, to open it: On the main menu, click Window and click the name of the file

On the main menu, click File -> Open File...

In the top section of the Code Editor, click the label that holds the name of the file

Opening a File

To open a file:

In the Solution Explorer, double-click the name of the file On the Standard toolbar, click the Open File button

This would display the Open File dialog box. From there, locate the file from its folder and click it.

Renaming a File

You can change the name of a file after starting a project. To do this, in the Solution Explorer, under the project that holds the file, right-click the file and click Rename. Type the desired name and press Enter.

Removing a File From a Project

If you have a file in a project but do not need that file anymore, you can delete it. To remove a file, in the Solution Explorer, under the project, right-click the name of the file and click Delete.

Practical Learning: Managing Files in a Project

1. If you are using Microsoft Visual Basic 2010 Express, in the Solution Explorer, right-click Module1.vb and click Delete. When asked whether you want to permanently delete, click OK.

In either studio, to add a new file, on the main menu, click Project -> Add New Item... 2. In the middle list, click Code File

(31)

4. Click Add

Writing Code

After creating or opening a file, you can add the necessary code to it. Microsoft Visual Basic ships with many skeleton codes you can use and customize. It writes the primary code for you and add all the necessary default behaviors. Once it has done this, you can change or remove any section. To access these code skeletons, in the section of the file where you want to add it, right-click and click Insert Snippet...:

(32)

In the menu that comes up, double-click a category:

Then double-click another category. This would display a list of code types:

If you see the type of code you want to use, double-click it.

In some cases, if you have already written some code, you may want to change it or rather add some code to it. The Code Editor provides some skeleton codes you can use. To use this approach, right-click the code you want to modify and click Surround With... In the list that appears, double-click the desired option.

Practical Learning: Writing Code

In the empty document, type the following:

(33)

Sub Main()

MsgBox("We are performing a general census of our population") End Sub

End Module

The Starting File of a Project

If you add many files to a project, you must specify what file should be processed first. If you create a console application using Microsoft Visual Studio or Microsoft Visual Basic 2010 Express, the first file you create is set as the default.

To specify the starting file of your project, on the main menu, click Project -> ProjectName Properties... In the Startup Object combo box, select the file.

Practical Learning: Specifying the Starting File of a Project

1. On the main menu, click Project -> GeneralCensus Properties

2. Click the arrow of the Startup Object combo box and select Statistics 3. To test the application, on the main menu, click Debug -> Start Debugging 4. Read the text of the message box

5. Click OK on the message box

Code Colors

Code is written in a wide area with a white background. This is the area you use the keyboard to insert code with common readable characters. The Code Editor uses some colors to differentiate categories of words or lines of text.

The colors used are highly customizable. To change the colors, on the main menu, you can click Tools -> Options... In the Options dialog box, in the Environment section, click Fonts and Colors. To set the color of a category, in the Display Items section, click the category. In the Item Foreground combo box, select the desired color. If you want the words of the category to have a colored background, click the arrow of the Item Background combo box and select one:

In both cases, the combo boxes display a fixed list of colors. If you want more colors, you can click a Custom button to display the Color dialog box that allows you to "create" a color.

Indentation

Indentation is another feature that makes your program easy to read. Indentation is a technique of grouping lines of code by category. To delimit the items of your code, you should indent them by two empty spaces or one tab. Indentation should be incremental. That is, when a line of code appears to be a child of the previous line, the new line should be indented.

(34)

To control the indentation of your code, on the main menu, click Tools -> Options... In the left list, Text Editor amd expand Basic. You can then use the options in VB Specify and Editor:

After making the changes, click OK to validate or Cancel to ignore.

Accessories for Code Writing

Comments

A comment is text that the compiler does not process when reading your code. As such, a comment can be written any way you want. In the Visual Basic language, the line that contains a comment can start with a single quote. Here is an example:

Module Module1 Sub Main()

' This line will not be considered as part of the code

End Sub End Module

(35)

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

Module Module1 Sub Main()

' This line will not be considered as part of the code Rem I can write anything I want on this line

End Sub End Module

Comments are very useful and you are strongly suggested to use comments regularly. They can never hurt your code and they do not 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.

White Spaces

When writing code, you will have to separate different parts with spaces, like the one between Sub and Main. This is referred to as white space. The amount of space you put between two words is not important. The compiler would ignore the white spaces between words. This means that Sub Main() and Sub Main() would the same effect. In the same way

Sub Main()

and

Sub Main()

would produce the same effect.

(36)

Operators and Operands

The Values of an Application

Introduction

When interacting with the computer, at times, a user might be asked to provide a value. At other times, the user might be presented with a value to manipulate. During this interaction, the values, any of them, are stored and retrieved at will. To make this possible, the computer uses its memory.

The computer memory is an area used to receive information, store it, and then make that information available when requested. The computer only makes its memory available to you. It doesn't know and cannot predict the type of value that your particular program would need. This is because one program might be made to manipulate numbers while another program might be made for names. Because the information stored in the computer can be as varied as possible, it may be segmented (the word segment is taken in its English meaning and not in its Assembly definition) in portions or various pieces.

The pieces of information stored in the computer memory come, go, and change on a regular basis. For this reason, a piece of information stored in the computer memory is called a variable. A variable is an area of the computer memory used to store a value. Because there can be many kinds of values stored in the computer memory, a variable stores only one kind of value.

The Stack

To manage the various types of values that can be used in a program, the computer is equipped with two types of memory. The Random Access Memory, also called RAM, is a type of memory that is "filled" with values when the computer comes up and while a person is using the computer. When the computer gets shut down, the RAM looses everything that was put in that memory so that the next time the computer comes up, the RAM "forgets" the values that were entered in it the previous time. In other words, when the computer boots up, the RAM is empty and new values must be entered in it.

Another type of memory that the computer uses is called Read-Only Memory (ROM). In this area, the computer stores values that "stick" in it and stay there. Such values can be called when needed and, unless they are explicitly deleted, when the computer gets shut down, the values go back to the ROM. The next time the computer comes up, the values of the ROM will be available. The values of the ROM stay there and are retrieved only when requested.

The RAM can be illustrated like a group of small boxes. When the computer boots up, or while the computer is coming up, they are empty:

Each one of these small boxes is named a bit. It can have only one of two values. From our illustrations, when the box is empty, the bit has a value of 0. When it is filled (it cannot be half-full or half-empty), it has a value of 1.

(37)

same way, when you start a program like Notepad, it is "loaded" in this memory. This means that part of the RAM is filled with some values. Some other parts of the RAM are filled with garbage or values that don't mean anything to you:

When your application comes up, you can ask the computer to put some values for your application. Remember that you are not, or your application is not, the only one that needs to use an area of the computer memory. Because there can be so many values that different applications store, retrieve, and manipulate all day long or as long as the computer is on, the operating system reserves an area of this memory for applications like yours. To make sure there is no mess, the computer is in charge of this area of memory. When you want to store a value in that memory, you let the computer know. The computer then puts (the verb used is "push") that value in the necessary area of the memory (the computer, and not you, decides where to put the value). When the value is not used anymore, the computer removes (the verb used is "pop") that value. This allows the computer to make that area of memory available to the applications that would need it. This area of memory that the computer reserves for the various applications, and is in charge of, is called the stack.

Variable Declaration

If you want to use an area of memory of the computer, in other words if you want to store a value in that memory, you must ask the compiler to reserve a portion of memory for your value. Making this request is referred to as declaring a variable. To formulate this request, you must first type the Dim keyword:

Dim

To make this request, you must provide a name for the variable. The name of a variable is also called an identifier. When the computer reserves an area of memory, it uses a name to be able to locate that area of memory. Later on, when you want to store a value in that memory, you will communicate a name to the compiler. The compiler will know the area of memory you are referring to by its name. This means that, at the right time, the name is used by both you and the compiler to know what portion of memory you are referring to. The name itself is not stored in the memory per se. It only allows you and the compiler to access a particular area of memory.

The Name of a Variable

There are rules you should, and usually must, follow when naming your variables. The rules to follow are:

The name of a variable can consist of only one a letter (a, b, c, d, e, f, g, h, i, f, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z. A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, or Z) The name of a variable can start with with a letter

The name of a variable can start with with an underscore _.

If the first character is an underscore, it must be followed by a letter

After the first character that is a letter or an underscore, the name can contain letters, underscores, or digits (0, 1, 2, 3, 4, 5, 6, 7, 8, or 9)

The name cannot have an empty space

The name cannot have any special character (! @ # $ % ^ & * + - = ~ ` < > , . : ; " ' { [ } ] | \ ) between letters or digits except the underscore as specified above. Some characters can be used as the last character of a name. We will encounter them when necessary

Can have up to 255 characters but refrain from using a name that is too long (more than 64 characters)

(38)

Must be unique inside of the procedure or the module it is used in

A name cannot be one of the words reserved for the Visual Basic language's own use. These words are also called keywords. Therefore, avoid using the following words to name a variable (this list includes official Visual Basic language keywords and words or expressions you should avoid):

AddHandler AddressOf Alias And AndAlso

Ansi As Assembly Auto Boolean

ByRef Byte ByVal Call Case

Catch CBool CByte CChar CDate

CDbl CDec Char CInt Class

CLng CObj Compare Const Continue

CSByte CShort CSng CStr CType

CUInt CULng CUShort Custom Date

Decimal Declare Default Delegate Dim

DirectCast Distinct Do Double Each

Else ElseIf

End EndIf Enum Equals Erase

Error Event Exit Explicit False

Finally For Friend From Function

Get GetType GetXmlNamespace GoSub GoTo

Group By Group Join Handles If Implements

Imports In Inherits Integer Interface

Into Is IsFalse IsNot IsTrue

Join Key Let Lib Like

Long Loop Me Mid Mod

Module MustInherit MustOverride MyBase MyClass

Namespace Narrowing New Next Not Nothing NotInheritable NotOverridable Object Of

Off On Operator Option Optional

Or Order By OrElse Overloads Overridable

Overrides ParamArray Partial Preserve Private

Property Protected Public RaiseEvent ReadOnly

ReDim REM RemoveHandler Resume Return

SByte Select Set Shadows Shared

Short Single Skip Skip While Static

Step Stop Strict String Structure Sub SyncLock Take Take While Text

Then Throw To True Try

TryCast TypeOf UInteger ULong Unicode

UShort Until Using Variant

Went When Where While Widening

With WithEvents WriteOnly Xor

Although you must always avoid using keywords as names of your variables in your program, if you insist on using one of these keywords to name something, put the word between square brackets. An example would be [True]

The Visual Basic language is not case sensitive. This means that NAME, name, and Name represent the same word. This means that, in the same section (normally called scope), you cannot have two variables with the same name that differ only by their cases. This would cause a name conflict. If you declare a variable in a scope and use it later with a different case, as

(39)

long as the same characters are used on both names, the Visual Basic compiler would know what variable you are referring to and there would not be any conflict.

Option Explicit

You should always make sure that you declare a variable before using it. Otherwise you may use two variables that seem to be different but because of a mistype, you would think that you are using two variables. Examples are Type and Tape.

To indicate to the compiler that each variable must be declared prior to being used, in the top section of your source file, you should type:

Option Explicit On

Values Fundamentals

Introduction

Besides the name, the second piece of information the compiler needs is the amount, also called size, of memory that the variable would need. This is because different values use different amounts of space. For example, the title of a book certainly needs more space than the number of pages of a daily newspaper.

The amount of space that a variable can occupy is referred to as its data type. To limit the amount of gymnastics to perform, the compiler uses categories of data types. For example, it can decide that a simple number would use one small "box" to store its value. On the other hand, it may decide that it would need ten "buckets" to store the title of a movie.

When you create a program, you can let the compiler know the amount of memory you would need for a particular variable. You can do this by specifying the most appropriate category. After telling the compiler that this particular variable would be used to store a number, you can change it in the middle of the program and decide to store an employee's maiden name. On the other hand, some numbers will require more space than others. For example, imagine you want to store the population of countries in a variable. In this case you would request memory that can hold a large number. This type of variable must be able to hold the population of China as well as the population of Burundi. Of course, this same space can hold the number of pages of a daily newspaper. This means that, sometimes, there will appear to be waste of memory. Nowadays, you should not be too concerned with memory as it is becoming less expensive: it is better to have a few empty "buckets" in the computer memory than to have unavailable memory.

To reduce the number of mistakes that could be due to a possible wrong value being stored in a variable, the Visual Basic compiler uses two mechanisms: variable initialization and conversion.

Practical Learning: Introducing Variables

1. Start Microsoft Visual Basic (either Microsoft Visual Studio or Microsoft Visual Basic 2010 Express)

2. To create a new application, on the main menu, click File -> New Project 3. In the middle list, click Console Application

4. Set the Name to YNB1 (which stands for Yugo National Bank 1) 5. Click OK

6. In the Solution Explorer, right-click Module1.vb and click Rename 7. Type the new name as Training.vb and press Enter

8. On the main menu, click Project -> YNB1 Properties

9. Click the arrow of the Application Type box and select Windows Forms Application 10. Click the Close button to close the Property Pages window

(40)

We saw that, to declare a variable, you use the Dim keyword, followed by a name. Here is an example: Module Exercise Sub Main() Dim Something End Sub End Module

After declaring a variable like this, the compiler reserves a portion of the computer memory for that variable but there may be two possible (small) problems: the compiler does not know how much space that variable would need to store its values and, because of this, the compiler would leave empty that area of memory.

To access the value of a variable, you can simply refer to its name. For example, you can display it to the user. We saw that you could use the MsgBox procedure to display a value. Here is an example: Module Exercise Sub Main() Dim Something Something = 25 MsgBox(Something) End Sub End Module

Practical Learning: Declaring Variables

To declare some variables, change the file as follows:

Module Training Sub Main() Dim CustomerName Dim AccountNumber Dim InitialDeposit End Sub End Module

Value Conversion

We mentioned that you could declare a variable but not specify the type of value that would be stored in the memory area reserved for it. When you have declared a variable, the compiler gives it an initial value. This is referred to as initializing the variable. Instead of the compiler doing it, you too can initialize a variable. Initialization partially solves the two problems we mentioned.

In reality, when you declare a variable, the compiler primarily considers it a string and reserves enough space to store any amount of characters. One way you can solve this confusion is to initialize the variable.

To initialize a variable, type its name, followed by =, and followed by the desired value. Here is an example: Module Exercise Sub Main() Dim Something Something = 25 End Sub End Module

After initializing the variable, the new value is stored in its reserved area of memory. When you initialize a variable, the compiler uses the given value to convert it to the appropriate type. For example, if you consider a variable with 25, it becomes considered an integral variable; that is, a variable whose memory can hold natural numbers.

(41)

We mentioned that, after declaring a variable, you could change its value whenever you judge it necessary. After declaring a variable as done in the above example, you can assign it any value of you choice. Here are examples:

Module Exercise Sub Main()

Dim Something Something = 25

MsgBox(Something)

Something = "Manchester United Football Club"

MsgBox(Something) Something = 237565.408

MsgBox(Something) End Sub

End Module

This is one of the unique features that make the Visual Basic (2005) language so flexible.

Requesting a Value

While many programs are meant to simply present values to the user, most applications are used to request values from the user. To make this possible and easy, Visual Basic provides a procedure called InputBox. To use it, type it, followed by parentheses. In its parentheses, enter a sentence that will serve as a guide to the user. The sentence itself should be included between double-quotes.

A typical sentence would indicate what value (or what type of value) you want the user to enter. Here is an example:

InputBox("Enter your first name: ")

The input box appears as a message box with the addition of a text box that would receive the user's value. Here is an example:

The user is expected to type a value in the text box. As mentioned for the variables, the value the user types is primarily considered a regular series of characters. To use that series, you must convert it to the appropriate type. We will review the procedures used to convert the values.

The InputBox() procedure provides more details. We will come back to it in Lesson 7.

Visual Basic Operations

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 values. 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.

(42)

If you plan to write a long piece of code, to make it easier to read, you may need to divide it in various lines. You can do it as you would in any text editor. Here is an example:

Module Exercise Sub Main()

Dim Something Something =

"Manchester United Football Club"

MsgBox(Something) End Sub

End Module

Notice that the variable Something and Manchester ... are written on different lines. As an alternative, you can use the line continuation operator represented by a white space followed by an underscore and an empty space. Here is an example:

Module Exercise Sub Main()

Dim Something Something = _

"Manchester United Football Club" MsgBox(Something)

End Sub End Module

The Parentheses: ()

Parentheses are used in two main circumstances: in a procedure as we have used Main,

MsgBox and InputBox so far, 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 Comma ,

The comma is used to separate variables used in a group. For example, a comma can be used to delimit the names of variables that are declared on the same line. Here is an example:

Module Exercise Sub Main()

Dim CustomerName, AccountNumber, InitialDeposit

Dim RegularDeposit, TotalDeposits

End Sub End Module

The comma can also be used to separate the member of an enumeration or the arguments of a method. We will review all of them when the time comes.

The Assignment Operator =

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

(43)

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.

The Double Quotes: ""

A double-quote is used to delimit a group of characters and symbols. To specify this delimitation, the double-quote is always used in combination with another double-quote, as in "". What ever is inside the quotes is the thing that need to be delimited. The value inside the double-quotes is called a string. Here is an example:

Sub Main() Dim Country

Country = "Grande Bretagne"

End Sub

If a procedure expects a string, you can type that string in the parentheses of the procedure, we will be using the MsgBox and InputBox procedures.

Practical Learning: Requesting Some Values

1. To use double-quotes and request some values, change the file as follows:

Module Training Sub Main()

Dim CustomerName Dim AccountNumber Dim InitialDeposit

CustomerName = InputBox("Enter Customer Name:") AccountNumber = InputBox("Enter Customer Acnt #:") InitialDeposit = InputBox("Enter Initial Deposit:") MsgBox("Yugo National Bank")

MsgBox(CustomerName) MsgBox(AccountNumber) MsgBox(InitialDeposit) End Sub

End Module

2. To test the program, on the main menu, click Debug -> Start Debugging 3. Enter the requested value as:

Enter Customer Name: Gertrude Monay Enter Customer Acnt #: 92-37293-30 Enter Initial Deposit: 450.00

4. When you have finished, return to your programming environment

The Colon Operator :

Most of the time, to make various statements easier to read, you write each on its own line. The Visual Basic language allows you to write as many statements as necessary on the same line. To do this, the statements can be separated by a colon. Here is an example:

Module Exercise Sub Main()

Dim CustomerName Dim AccountNumber Dim InitialDeposit

CustomerName = InputBox("Enter Customer Name:") AccountNumber = InputBox("Enter Customer Acnt #:") InitialDeposit = InputBox("Enter Initial Deposit:") MsgBox("Yugo National Bank") : MsgBox(CustomerName) MsgBox(AccountNumber) : MsgBox(InitialDeposit) End Sub

(44)

String Concatenation: &

The & operator is used to append two strings 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:

Sub Main() Dim FirstName Dim LastName Dim FullName FirstName = "Francis " LastName = "Pottelson"

FullName = FirstName & LastName 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.

Practical Learning: Concatenating Some Strings

1. To use the string concatenator, change the file as follows:

Module Training Sub Main()

Dim CustomerName Dim AccountNumber Dim InitialDeposit

CustomerName = InputBox("Enter Customer Name:") AccountNumber = InputBox("Enter Customer Acnt #:") InitialDeposit = InputBox("Enter Initial Deposit:") MsgBox("Yugo National Bank")

MsgBox("Customer Name: " & CustomerName) MsgBox("Account Number: " & AccountNumber) MsgBox("Initial Deposit: $" & InitialDeposit)

End Sub End Module

2. To test the program, on the main menu, click Debug -> Start Debugging

3. Enter the requested value and, when you have finished, return to your programming environment

Tabs and Carriage Return

Carriage Return-Line Feed

If you are displaying a string but judge it too long, you can segment it in appropriate sections as you see fit. To do this, you can use vbCrLf.

Practical Learning: Using Carriage Return-Line Feed

1. To use the Carriage Return-Line Feed, change the file as follows:

Module Training Sub Main() Dim CustomerName Dim AccountNumber Dim InitialDeposit Dim Result

CustomerName = InputBox("Enter Customer Name:") AccountNumber = InputBox("Enter Customer Acnt #:") InitialDeposit = InputBox("Enter Initial Deposit:")

(45)

Result = " =-= Yugo National Bank =-=" & vbCrLf & "Customer Name: " & CustomerName & vbCrLf & "Account Number: " & AccountNumber & vbCrLf & "Initial Deposit: $" & InitialDeposit

MsgBox(Result) End Sub

End Module

2. To test the program, on the main menu, click Debug -> Start Debugging 3. Enter the requested values. Here are examples:

4. When you have finished, return to your programming environment

Carriage Return-Line Feed

From your experience with using the computer keyboard, you probably know already that, to create a tab white space, you can press the Tab key. If you want to get the same effect in the results you present to the user, you can use the vbTab operator of the Visual Basic language. Here are examples:

(46)

Sub Main() Dim FirstName Dim LastName Dim FullName FirstName = "Francis " LastName = "Pottelson"

FullName = LastName & ", " & FirstName

MsgBox("First Name: " & vbTab & FirstName & vbCrLf & "Last Name: " & vbTab & LastName & vbCrLf & "Full Name: " & vbTab & FullName)

End Sub

This would produce:

In the same way, you can create as many vbTab combinations as necessary.

Unary Operators

Positive Unary 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.

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.

(47)

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 as in MondayHours + TuesdayHours to get a total number of hours worked on Monday and Tuesday.

Besides arithmetic operations, the + symbol can also be used to concatenate strings, that is, to add one string to another. This is done by appending one string at the end of another. Here is an example: Module Exercise Sub Main() Dim FirstName Dim LastName Dim FullName FirstName = "James " LastName = "Fame"

FullName = FirstName + LastName

MsgBox("Full Name: " & FullName) End Sub

End Module

Practical Learning: Using the Addition Operator

1. To use the addition, change the file as follows:

Module Training Sub Main() Dim CustomerName Dim AccountNumber Dim InitialDeposit Dim RegularDeposit Dim TotalDeposits Dim Result

CustomerName = "Paul Bertrand Yamaguchi" AccountNumber = "52-92074-95"

InitialDeposit = 325 RegularDeposit = 750

TotalDeposits = InitialDeposit + RegularDeposit Result = " =-= Yugo National Bank =-=" & vbCrLf & "Customer Name: " & CustomerName & vbCrLf & "Account Number: " & AccountNumber & vbCrLf &

"Total Deposits: $" & (InitialDeposit + RegularDeposit) MsgBox(Result)

End Sub End Module

2. To execute the application, press F5

3. After using the program, return to your programming environment

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

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.

(48)

1. To subtract, change the file as follows:

Module Training Sub Main()

Dim CustomerName, AccountNumber Dim InitialDeposit, Withdrawals Dim RegularDeposit, TotalDeposits Dim CurrentBalance

Dim Result

CustomerName = "Henriette Jolana" AccountNumber = "84-48662-72" InitialDeposit = 1500

RegularDeposit = 468.75

TotalDeposits = InitialDeposit + RegularDeposit Withdrawals = 300

CurrentBalance = TotalDeposits - Withdrawals Result = " =-= Yugo National Bank =-=" & vbCrLf & "Customer Name: " & CustomerName & vbCrLf & "Account Number: " & AccountNumber & vbCrLf &

"Total Deposits: $" & (InitialDeposit + RegularDeposit) & vbCrLf &

"Withdrawals: $" & Withdrawals & vbCrLf & "Current Balance: $" & CurrentBalance

MsgBox(Result) End Sub

End Module

2. To execute the program, press F5

3. Return to your programming environment

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.

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.

References

Related documents