Visual Basic - NET by Saad
Visual Basic - NET by Saad
Before we begin learning Visual Basic 6 programming, let us understand some basic
concepts of programming. Programming means designing a set of instructions to ask
the computer to carry out certain jobs that are very much faster and more efficient than
human beings can do. As the mirochips of a CPU can only understand 0 and 1 in the
binary system, the earliest programming language uses combinations of 0 and 1 code
to communicate with computer, a language that is called machine language. Machine
language is extremely difficult to learn . Fortunately , scientists have invented human
language-like program languages or high level programming languges which are much
easier to master. Some of the high level programming languages are Fortran, Cobol,
Java, C, C++, c#, Visual Basic,Turbo Pascal, flash action script, JavaScript,HTML and
more.
VISUAL BASIC is a high level programming language which evolved from the earlier
DOS version called BASIC. BASIC means Beginners' All-purpose Symbolic Instruction
Code. It is a relatively easy programming language to learn. The code looks a lot like
English Language. Different software companies produced different versions of BASIC,
such as Microsoft QBASIC, QUICKBASIC, GWBASIC ,IBM BASICA and so on.
However, people prefer to use Microsoft Visual Basic today, as it is a well developed
programming language and supporting resources are available everywhere. Now, there
are many versions of VB exist in the market, the most popular one and still widely used
by many VB programmers is none other than Visual Basic 6 . We also have VB.net,
Visual Basic 2005, Visual Basic 2008 , Visual Basic 2010, Visual Basic 2012 and Visual
Basic 2013 . VB2008, VB2010, VB2012 and VB2013 are fully object oriented
programming (OOP) languages.
VISUAL BASIC is also a VISUAL and Event-driven Programming Language. These are
the main divergence from the old BASIC. In BASIC, programming is done in a text-only
environment and the program is executed sequentially. In VB6, programming is done in
a graphical environment. In the old BASIC, you have to write program code for each
graphical object you wish to display it on screen, including its position and its color.
However, In VB6 , you just need to drag and drop any graphical object anywhere on the
form, and you can change its properties using the properties window.
With VB 6, you can create any program depending on your objective.For math teachers,
you can create mathematical programs such as Geometric Progression, Quadratic
Equation Solver, Simultaneous Equation Solver ,Prime Number, Factors Finder,
Quadratic Function Graph Plotter and so on. For science teachers, you can create
simulation programs such as Projectile, Simple Harmonic Motion, Star War etc. If you
are in business, you can also create business applications such as inventory
management system , Amortization Calculator , investments calculator, point-of-sale
system, payroll system, accounting program and more to help manage your business
and increase productivity. For those of you who like games , you can create those
programs such as slot machine, reversi, tic tac toe and more. Besides, you can create
multimedia programs such as Smart Audio Player, Multimedia Player and more.
Indeed, there is no limit to what program you can create ! We offer many sample codes
in our tutorial.
After installing vb6 compiler, the icon with appear on your desktop or in your programs
menu. Click on the icon to launch the VB6 compiler. On start up, Visual Basic 6.0 will
display the following dialog box as shown in Figure 1.1.
You can choose to either start a new project, open an existing project or select a list of
recently opened programs. A project is a collection of files that make up your
application. There are various types of applications that we could create, however, we
shall concentrate on creating Standard EXE programs (EXE means executable). Before
you begin, you must think of an application that might be useful, have commercial
values . educational or recreational. click on the Standard EXE icon to go into the actual
Visual Basic 6 programming environment.
When you start a new Visual Basic 6 Standard EXE project, you will be presented with
the Visual Basic 6 Integrated Development Environment (IDE). The Visual Basic 6
Integrated Programming Environment is show in Figure 1.2. It consists of the toolbox,
the form, the project explorer and the properties window.
Form is the primary building block of a Visual Basic 6 application. A Visual Basic 6
application can actually comprises many forms; but we shall focus on developing an
application with one form first. We will learn how to develop applications with multiple
forms later. Before you proceed to build the application, it is a good practice to save the
project first. You can save the project by selecting Save Project from the File menu,
assign a name to your project and save it in a certain folder.
Commercial GUI Design/Development Approach
Modern programs run in a graphical user interface (GUI) environment. You can open up any desktop
program or web browser and examine the GUI. This interface includes:
Buttons (some with Icons and Graphical Images) and Menus on which you point and click.
TextBox controls in which you type information.
Graphical images to guide a system user in using the program.
Other components.
A GUI for a version of Microsoft Word is shown in this figure.
Visual Basic,
Visual C# (C sharp),
Visual C++ (cee-plus-plus),
Visual F# (F sharp),
JScript and
Web Development (called ASP.NET).
It also includes the .NET 4 Framework upon which these languages
operate.
Visual Basic (also termed Visual Basic.NET or VB) is a major revision of earlier Microsoft VB products.
VB is available in several editions including the free Express Edition that you can download from
Microsoft. Other editions (Professional, Premium, and Ultimate) are used within industry.
.NET Framework Class Library. This is a library of predefined class objects. It enables you to
quickly build a computer application through the use of predefined objects such as forms, text
boxes, labels, buttons, drop-down list controls, and others (mandatory).
Common Language Runtime (CLR). This component manages the execution of a programming
project written in any of the languages that are included within Visual Studio including Visual
Basic as a language (mandatory). This component is installed as part of the .NET Framework.
MSDN (Help). This is the help component and provides access to a help reference library. This
is covered in detail at the end of this set of notes. It is an optional, but highly recommended
component.
VB is also termed an event-driven programming language because you will write program code that
responds to events that are controlled by the system user. Example events include:
In order to work with VB, you need to understand "object" terminology as defined in Table 1.
Table 1
Terminology Definition
Object A thing – like a noun in English. Examples include forms and controls you place on forms
such as buttons, text boxes, and icons.
Property Objects have properties – like adjectives in English. Properties describe object behaviors.
Examples of properties include Text, Name, BackColor, Font, and Size.
Each new object you create is defined based on its class – the new object is called a class
instance.
The programming applications you will design and develop are called solutions in VB.
A solution can actually contain more than one project, but in this course we will focus on just
creating a single project in a solution.
Each solution is stored in a folder identified by the solution name.
This is covered in more detail later in this set of notes.
Before Using Visual Basic
When you first startup a computer in our classroom and computer laboratories, you may need to reset
the Properties of My Documents.
Required because the operating system setup on these classroom/lab computers is produced
from a “ghost image” created by the system administrator.
At the desktop, right-click on the My Documents icon.
Select the Properties menu option as shown in this figure.
Click the Restore Defaults button and then OK as shown in the below figure – this sets the
ownership to you as the logged in user of the computer.
Do this each time you plan to use VB in the classroom or computer lab – this is NOT necessary
when using VB on your home computer.
Launching Visual Basic
Start VB – Click the Windows Start button and locate Microsoft Visual Studio 2010 – launch the
program by clicking. The option will look something like this.
The first screen to display may require you to choose your Default Environment Settings.
The Visual Studio Start Page is shown in the figure below. The start page is slightly different for Visual
Studio 2010 (Professional or Ultimate Edition) and Visual Basic 2010 Express Edition.
This is the Start Page for Visual Basic 2010 Express Edition.
This is the Start Page for Visual Studio 2010 (Ultimate Edition).
Click the New Project link shown in the figure above to create a new project. This opens the New
Project dialog box shown below.
Your first project will be a Visual Basic Project using a Windows Forms Application template as
shown in the figures above.
The default name is WindowsApplication1 -- not a very useful name. Change the project name
to: Ch01VBUniversity.
Click the OK button – it takes several seconds to create the project files from the template.
Across the top are menus with different options used in the designing of an application.
Toolbars with shortcut icons are shown below the menus.
Form Designer (also termed the Document Window).
o Displays open documents such as the Form1 shown in the figure
below.
o Tabs along the top are used to allow you to switch rapidly between
open documents.
o Every project starts with a default form named Form1 – the form
you modify to build your business application.
o The form can be resized by using the sizing handles.
o The form can be renamed (you’ll do this later in an exercise).
Solution Explorer Window – displays filenames for files that comprise a project. The solution
name is also shown here (Ch01VBUniversity).
Properties Window – displays properties of the currently selected object – in the figure the
properties displayed are those of the Form object.
ToolBox Window – this is shown along the left edge of the figure in collapsed display.
The Toolbox
The Toolbox:
You can also close/open these windows with the View menu.
Most developers use Visual Basic to create a COM component that works with
ArcMap or ArcCatalog. Earlier in the Getting Started section of the help you
learned that since the ESRI applications are COM clients—their architecture
supports the use of software components that adhere to the COM specification—
you can build components with different languages, including Visual Basic.
These components can then be added to the applications easily. For information
about packaging and deploying COM components that you've built with Visual
Basic, see the Packaging and Deploying Customizations topic.
This section is not intended as a Visual Basic tutorial; rather, it highlights aspects
of Visual Basic that you should know in order to be effective when working with
ArcObjects.
In Visual Basic you can build a COM component that will work with ArcMap or
ArcCatalog by creating an ActiveX DLL. This section will review the rudimentary
steps involved. Note that these steps are not all-inclusive. Your project may
involve other requirements.
1. Start Visual Basic. In the New Project dialog box, create an ActiveX DLL Project.
2. In the Properties window, make sure that the Instancing property for the initial class
module and any other class modules you add to the Project is set to 5—MultiUse.
3. Reference the ESRI Object Library.
4. Implement the required interfaces. When you implement an interface in a class
module, the class provides its own versions of all the public procedures specified in
the type library of the interface. In addition to providing a mapping between the
interface prototypes and your procedures, the Implements statement causes the
class to accept COM QueryInterface calls for the specified interface ID. You must
include all the public procedures involved. A missing member in an implementation
of an interface or class causes an error. If you don't put code in one of the
procedures in a class you are implementing, you can raise the appropriate error
(Const E_NOTIMPL = &H80004001). That way, if someone else uses the class, they'll
understand that a member is not implemented.
Visual Basic automatically generates the necessary GUIDs for the classes,
interfaces, and libraries. Setting binary compatibility forces VB to re-use
the GUIDs from a previous compilation of the DLL. This is essential since
ArcMap stores the GUIDs of commands in the document for subsequent
loading.
Implementing interfaces
Inbound interfaces are supported with the Implements keyword. However, unlike
the outbound interface, all the methods defined on the interface must be stubbed
out. This ensures that the vTable is correctly formed when the object is
instantiated. Not all of the methods have to be fully coded, but the stub functions
must be there. If the implementation is blank an appropriate return code should
be given to any client to inform them that the method is not implemented (see the
section Working With HRESULTs in the "The Visual Basic Environment
(General)" topic). To implement the IExtension interface, code similar to that
below is required. Note all the methods are implemented.
The principle difference between working with the VBA development environment
embedded in the applications and working with Visual Basic is that the latter
environment requires that you load the appropriate object libraries so that any
object variables that you declare can be found. If you don't add the reference,
you'll get the error message to below. In addition, the global variables
ThisDocument and Application are not available to you.
In all cases, you'll need to load the ESRI Object Library esriCore.olb. Depending on what
you want your code to do, you may add other ESRI object libraries, perhaps for one of the
extensions.
To display the References dialog box in which you can set the references you
need, select References in the Visual Basic Project menu.
After you set a reference to an object library by selecting the check box next to its
name, you can find a specific object and its methods and properties in the Object
Browser.
The References dialog.
If you are not using any objects in a referenced library, you should clear the
check box for that reference to minimize the number of object references Visual
Basic must resolve, thus reducing the time it takes your project to compile. You
should not remove a reference for an item that is used in your project.
You can't remove the "Visual Basic for Applications" and "Visual Basic objects
and procedures" references because they are necessary for running Visual
Basic.
Referring to a document
Implements IExtension
Private m_pApp As IApplication
Implements ICommand
Private m_pApp As IApplication
Singletons are objects that only support one instance of the object. These objects
have a class factory that ensures that anytime an object is requested, a pointer to
an already existing object is returned.
You must be careful to ensure that this object is only used where the
implementation will only ever run within ArcMap and ArcCatalog. For instance, it
would not be a good idea to make use of this function from within a custom
feature, since that would restrict what applications could be used to view the
feature class.
You can start ArcMap from the command line and pass it an argument that is
either the pathname of a document (.mxd) or the pathname of a template (.mxt).
In the former case, ArcMap will open the document; in the latter case ArcMap will
create a new document based on the template specified.
You can also pass an argument and create an instance of ArcMap by supplying
arguments to the Win32 API's ShellExecute function or Visual Basic's Shell
function, as follows.
In Visual Basic, it is not possible to determine the command line used to start the
application. There is a sample on disk that provides this functionality. It can be
found at \arcgis\arcexe83\ArcObjects Developer
Kit\samples\COMTechniques\Command Line.
To execute a program and wait until it is terminated, you must call three Win32
API functions. First, call the CreateProcessA function to load and execute
ArcMap. Next, call the WaitForSingleObject function, which forces the operating
system to wait until ArcMap has been terminated. Finally, when the user has
terminated the application, call the CloseHandle function to release the
application's 32-bit identifier to the system pool.
Visual Basic has a debugger integrated into its development environment. This is
in many cases a valuable tool when debugging Visual Basic code, however, in
some cases it is not possible to use the VB debugger. The use of the debugger
and these special cases are discussed below.
In many cases, the Visual Basic debugger will work without any problems,
however there are two problems when using the debugger that is supplied with
Visual Basic 6. Both of these problems exist because of the way that Visual
Basic implements its debugger.
Normally when running a tool within ArcMap, the DLL is loaded into ArcMap's
address space and calls are made directly into the DLL. When debugging this is
not the case. Visual Basic makes changes to the registry so that the CLSID for
your DLL does not point to your DLL, but instead it points to the Visual Basic
Debug DLL (VB6debug.dll). The Debug DLL must then support all the interfaces
implemented by your class on the fly. With the VB Debug DLL loaded into
ArcMap, any method calls that come into the DLL are forwarded on to Visual
Basic where the code to be debugged is executed. The two problems with this
are caused by the changes made to the Registry and the cross-process space
method calling. When these restrictions are first encountered it can be confusing
since the object works outside the debugger, or at least until it hits the area of
problem code.
Since the method calls made from ArcMap to the custom tool are across
apartments, there is a requirement for the interfaces to be marshaled. This
marshalling causes problems in certain circumstances. Most data types can be
automatically marshaled by the system, but there are a few that require custom
code, because the standard marshaler does not support the data types. If one of
these data types is used by an interface within the custom tool and there is no
custom marshalling code, the debugger will fail with an "Interface not supported
error".
The registry manipulation also breaks the support for component categories. Any
time there is a request on a component category, the category manager within
COM will be unable to find your component, because rather than asking whether
your DLL belongs to the component category, COM is asking whether the VB
debugger DLL belongs to the component category, which obviously it doesn't.
What this means is that anytime a component category is used to automate the
loading of a DLL, the DLL cannot be debugged using the Visual Basic debugger.
This obviously causes problems for many of the ways to extend the framework.
The most common way to extend the framework is to add a command or tool.
Previously it was discussed how component categories were used in this
instance. Remember the component category was only used to build the list of
commands in the dialog box. This means that if the command to be debugged is
already present on a toolbar the Visual Basic debugger can be used. Hence, the
procedure for debugging Visual Basic objects that implement the ICommand
interface is to ensure that the command is added to a toolbar when ArcMap is
executed standalone, and then, after saving the document, loading ArcMap
through the debugger.
In some cases, like extensions and property pages, it is not possible to use the
Visual Basic debugger. If you have access to the Visual C++ Debugger you can
use one of the options outlined below. Fortunately, there are a number of ESRI
Visual Basic Add-ins that make it possible to track down the problem quickly and
effectively. The add-ins described in the topic ESRI Add-Ins for Visual Basic,
provide error log information, including line and module details. A sample output
from an error log is given below; note the call stack information along with line
numbers.
If the Visual Basic debugger and add-ins do not provide enough information, the
Visual C++ debugger can be used, either on its own or with C++ ATL wrapper
classes. The Visual C++ debugger does not run the object to be debugged out of
process from ArcMap, which means that none of the above issues apply.
Common debug commands are given in the section Debugging Tips In
Developer Studio in the "The Visual C++ Environment" topic. Both of the
techniques below require the Visual Basic project to be compiled with Debug
Symbol information.
The Visual C++ Debugger can work with this symbolic debug information and the
source files.
It is possible to use the Visual C++ debugger directly by attaching to a running process that
has the Visual Basic object to be debugged loaded, and then setting a breakpoint in the
Visual Basic file. When the line of code is reached, the debugger will halt execution and step
you into the source file at the correct line. The required steps are shown below.
No changes can be made to the source code within the debugger, and variables
cannot be inspected, but code execution can be viewed and altered. This is often
sufficient to determine what is wrong, especially with logic-related problems.
UNIT-2
Introduction to Variables
Overview
When you write a program as a time sheet, you may decide that a user will type her weekly
hours in one box and her salary in another box; then another box will display her weekly
salary. When you are designing the program, you cannot predict the names of the people who
will be using the program and you definitely cannot know the weekly hours they will get week
after week. What you have to do is ask the computer to create temporary storage areas that
one user can use while the program is running. If that box can be used to store a salary, when
another user is using the same program, that box should be ready to receive new inputs, new
salary for that other user.
The computer memory is made of small storage areas used to hold the things that a program
needs while it is running. As a programmer, you specify these things, or you provide them to
the computer; the computer then puts them in these storage areas. When you need one of
them, you let the computer know. The machine located it and makes it available to you to use
as you see fit.
A variable is a value you are ask the computer to store in its memory while the program is
running.
Using a Variable
As stated already, a variable is an area of computer memory you use in your program. To use
a variable, you must give it a name. There are rules you should, and usually must, follow
when naming your variables. The name of a variable:
BackColor = SomeColor
End Sub
Variable Declaration
Unlike languages referred to as strongly typed, Visual Basic is so flexible you can use any
variable just by specifying its name. When you provide this name, the computer directly
creates an area in memory for it. Based on this, consider the following code section:
SomeColor = vbRed
SumColor = vbRed
BackColor = SameColor
End Sub
SomeColor = vbRed
SumColor = vbGreen
BackColor = SumColor
End Sub
SumColor = vbGreen
BackColor = SomeColor
End Sub
If you execute this program, when the form displays, it would be painted in red. If the user
clicks the form, it would be painted in blue. If the user presses a key, the form would be
painted in green. There is some confusion in the program. It uses a variable that seems to
have a name but initialize three times with different colors. Visual Basic allows you to directly
use any name for a variable as you see fit. Fortunately, to eliminate the possibility of this
confusion, you can first let Visual Basic know that you will be using a certain variable.
Informing Visual Basic about a variable prior to using that variable is referred to as declaring a
variable. When a variable has been declared, just like the variable not declared, the computer
reserves an area of memory for it.
Dim
On the right side of Dim, you must type a name for the variable, following the same rules we
reviewed above. Here is an example of declaring and using a variable:
BackgroundColor = vbRed
BackColor = BackgroundColor
End Sub
Declaring a variable simply communicates to Visual Basic the name of that variable. You can
still use a mix of declared and not-declared variable. This is demonstrated in the following
event:
Once again, the compiler believes that you are using two variables; one is called
BackgroundColor and the other is called SomeColor. This can still create a great deal of
confusion because you may be trying to use the same variable referred to twice. The solution
to this possible confusion is to tell Visual Basic that a variable cannot be used if it has not been
primarily declared. To communicate this, on top of each file you use in the Code Editor, type
Option Explicit
This can also be done automatically for each file by checking the Require Variable Declaration in
the Options dialog box.
3. Click OK
4. Close Visual Basic without saving the project
5. Start Microsoft Visual Basic and create a new application using Standard EXE
6. Right-click the form and click View Code
7. In the Code Editor, click the arrow of the Object combo box and select Form
8. To use a variable, implement the Load event as follows:
9. Press F5 to test the application
10. Notice that you receive an error:
11. Click OK
BackgroundColor = vbRed
BackColor = BackgroundColor
End Sub
Introduction
When you decide to use a variable, you are in fact asking the computer to use a certain amount
of space to hold that variable. Since different variables will be used for different purposes, you
should specify the kind of variable you intend to use, then the computer will figure out how
much space is needed for a particular variable. Each variable you use will utilize a certain
amount of space in the computer's memory.
Before declaring or using a variable, first decide what kind of role that variable will play in your
program. Different variables are meant for different situations. The kind of variable you want to
use is referred to as a data type. To specify the kind of variable you want to use, you type the
As keyword on the right side of the variable's name. The formula to declare such a variable is:
Once you know what kind of variable you will need, choose the appropriate data type. Data
types are organized in categories such as numbers, characters, or other objects.
String
A string is an empty text, a letter, a word or a group of words considered. To declare a string
variable, use the String data type. Here is an example:
After declaring the variable, you can initialize. If you want its area of memory to be empty, you
can assign it two double-quotes. Here is an example:
CountryName = ""
End Sub
If you want to store something in the memory space allocated to the variable, assign it a word
or group of words included between double-quotes. Here is an example:
Boolean
A Boolean variable is one whose value can be only either True or False. To declare such a
variable, use the Boolean keyword. Here is an example:
After declaring a Boolean variable, you can initialize by assigning it either True or False. Here is
an example:
IsMarried = False
End Sub
Like any other variable, after initializing the variable, it keeps its value until you change its
value again.
Introduction
A natural number is one that contains only one digit or a combination of digits and no other
character, except those added to make it easier to read. Examples of natural numbers are 122,
8, and 2864347. When a natural number is too long, such 3253754343, to make it easier to
read, the thousands are separated by a special character. This character depends on the
language or group of language and it is called the thousands separator. For US English, this
character is the comma. The thousands separator symbol is mainly used only to make the
number easier to read.
Byte
A byte is a small natural positive number that ranges from 0 to 255. A variable of byte type
can be used to hold small values such as a person's age, the number of fingers on an animal,
etc.
To declare a variable for a small number, use the Byte keyword. Here is an example:
Integer
An integer is a natural number larger than the Byte. It can hold a value between
-32,768 and 32,767. Examples of such ranges are: the number of pages of a book.
To declare a variable of type integer, use the Integer keyword. Here is an example:
To declare a variable that can hold a very large natural number, use the Long keyword. Here is
an example:
Introduction
A real number is one that displays a decimal part. This means that the number can be made of
two sections separated by a symbol that is referred to as the Decimal Separator or Decimal
Symbol. This symbol is different by language, country, group of languages, or group of
countries. In US English, this symbol is the period as can be verified from the Regional (and
Language) Settings of the Control Panel of computers of most regular users:
On both sides of the Decimal Symbol, digits are used to specify the value of the number. The
number of digits on the right side of the symbol determines how much precision the number
offers.
Single
A single is a decimal number whose value can range from –3.402823e38 and –1.401298e-45 if
the number is negative, or 1.401298e-45 and 3.402823e38 if the number is positive.
To declare a variable that can hold small decimal numbers with no concern for precision, use
the Single data type. Here is an example:
To declare a variable that can store large decimal numbers with a good level of precision, use
the Double keyword.
Date
A date is a numeric value that represents the number of days that have elapsed since a
determined period. A time is a numeric value that represents the number of seconds that have
elapsed in a day.
To declare a variable that can hold either date values, time values, or both, use the Date
keyword. After the variable has been declared, you will configure it to the appropriate value.
Here are two examples:
Variant
A Variant can be used to declare any kind of variable. You can use a variant when you can't
make up your mind regarding a variable but, as a beginning programmer, you should avoid it.
Here is a table of various data types and the amount of memory space each one uses:
4.94065645841247E – 324 to
1.79769313486231E308 (positive values)
Using Variables
We also saw that we can declare different variables each on its own line as follows;
If you have many variables of the same data type, you can declare them on the same line,
each separated with a comma. Remember to specify their common type. Here is an example:
When naming your variables, besides the above suggestions, you can start a variable's name
with one to three-letter prefix that could identify the data type used. Here are a few
suggestions:
Constants
Introduction
A constant is a value that doesn't change. There are two types of constants you will use in
your programs: those supplied to you and those you define yourself.
The example on the previous page would run just as well if you didn't declare your variables:
If you comment out the variable declarations like this, your macro will still work.
In the above case, VBA will reach the first two lines creating variables:
HeroName = Range("C4")
HeroRating = Range("C6")
Because you haven't explicitly declared HeroName and HeroRating, VBA will create them on the fly for you,
giving each the type Variant. So far, so good?
Well, yes - until you mistype a variable name. Here's what would happen for a simple mistyping:
There's a misprint here - how quickly can you see it? The superhero you get as a result
The problem above could be avoided so easily, if you could just tell VBA that wherever you use a variable, you have to
declare it. Read on!
The solution to the above problem is to include two magic words at the top of each module - Option Explicit:
Option Explicit
Sub RecordVote()
'the name of each superhero and their rating
'Dim HeroName As String
'the rating assigned to them
'Dim HeroRating As Long
'go to the votes sheet and get the value of the superhero, and their rating
Worksheets("Votes").Select
HeroNane = Range("C4").Value
HeroRating = Range("C6").Value
Here's what you get if you run the above macro now:
The result of running the macro. VBA highlights the variable you've misspelt, and tells you that it's not defined.
Given that forcing yourself to declare all variables like this is such a good idea, how can you avoid having to
type in Option Explicit at the top of every new module you create? Here's how!
1. From the menu within VBA (not Excel) select Tools -> Options.
2. Tick the Require Variable Declaration box shown below.
3. Select OK .
Tick the box shown!
From now on, every time you create a new module it will have the words Option Explicit at the top, and you'll
have to declare any variables that you use.
An expression is a series of value elements combined with operators, which yields a new value.
The operators act on the value elements by performing calculations, comparisons, or other
operations.
Types of Operators
Visual Basic provides the following types of operators:
Arithmetic Operators perform familiar calculations on numeric values, including shifting their
bit patterns.
Comparison Operators compare two expressions and return a Boolean value representing
the result of the comparison.
Concatenation Operators join multiple strings into a single string.
Logical and Bitwise Operators in Visual Basic combine Boolean or numeric values and
return a result of the same data type as the values.
The value elements that are combined with an operator are called operands of that operator.
Operators combined with value elements form expressions, except for the assignment operator,
which forms a statement. For more information, see Statements in Visual Basic.
Evaluation of Expressions
The end result of an expression represents a value, which is typically of a familiar data type such
as Boolean, String, or a numeric type.
5+4
15 * System.Math.Sqrt(9) + x
763 < 23
' The preceding expression evaluates to False.
Several operators can perform actions in a single expression or statement, as the following
example illustrates.
VB
x = 45 + y * z ^ 2
In the preceding example, Visual Basic performs the operations in the expression on the right side
of the assignment operator (=), then assigns the resulting value to the variable x on the left. There
is no practical limit to the number of operators that can be combined into an expression, but an
understanding of Operator Precedence in Visual Basic is necessary to ensure that you get the
results you expect.
An operator is a special symbol which indicates a certain process is carried out. Operators in
programming languages are taken from mathematics. Programmers work with data. The
operators are used to process data.
Arithmetic operators
Boolean operators
Relational operators
Bitwise operators
An operator may have one or two operands. An operand is one of the inputs (arguments) of an
operator. Those operators that work with only one operand are called unary operators. Those
who work with two operands are called binary operators.
Option Strict On
Module Example
Sub Main()
Console.WriteLine(2)
Console.WriteLine(-2)
Console.WriteLine(2+2)
Console.WriteLine(2-2)
End Sub
End Module
The + and - signs can be addition and subtraction operators as well as unary sign operators. It
depends on the situation.
Option Strict On
Module Example
Dim a As Byte
Sub Main()
a = 1
Console.WriteLine(-a) ' Prints -1
Console.WriteLine(-(-a)) ' Prints 1
End Sub
End Module
The plus sign can be used to indicate that we have a positive number. But it is mostly not used.
The minus sign changes the sign of a value.
Option Strict On
Module Example
Dim a As Byte
Dim b As Byte
Sub Main()
a = 3 * 3
b = 2 + 2
End Sub
End Module
Multiplication and addition operators are examples of binary operators. They are used with two
operands.
The assignment operator = assigns a value to a variable. A variable is a placeholder for a value. In
mathematics, the = operator has a different meaning. In an equation, the = operator is an equality
operator. The left side of the equation is equal to the right one.
x = 1
Console.WriteLine(x) ' Prints 1
x = x + 1
Console.WriteLine(x)
The previous expression does not make sense in mathematics. But it is legal in programming. The
expression adds 1 to the x variable. The right side is equal to 2 and 2 is assigned to x.
3 = x
This code example results in syntax error. We cannot assign a value to a literal.
Arithmetic operators
Symbol Name
+ Addition
- Subtraction
* Multiplication
/ Division
\ Integer Division
Mod Modulo
^ Exponentiation
Option Strict On
Module Example
Dim a As Byte
Dim b As Byte
Dim c As Byte
Sub Main()
a = 10
b = 11
c = 12
add = a + b + c
sb = c - a
mult = a * b
div = CType(c / 3, Byte)
Console.WriteLine(add)
Console.WriteLine(sb)
Console.WriteLine(mult)
Console.WriteLine(div)
End Sub
End Module
In the preceding example, we use addition, subtraction, multiplication and division operations.
This is all familiar from the mathematics.
$ ./arithmetic.exe
33
2
110
4
Next we will show the distinction between normal and integer division.
Option Strict On
Module Example
Dim a As Single = 5
Dim b As Single = 2
Dim c As Single
Sub Main()
c = 5 / 2
Console.WriteLine(c)
c = 5 \ 2
Console.WriteLine(c)
End Sub
End Module
In the preceding example, we divide two numbers using normal and integer division operator.
Visual Basic has two distinct operators for division.
Dim a As Single = 5
This is integer division. The result of this operation is always and integer. The c variable has value
2.
$ ./division.exe
2.5
2
The last two operators that we will mention are modulo operator and exponentiation operator.
The Mod operator is called the modulo operator. It finds the remainder of division of one number
by another. 9 Mod 4, 9 modulo 4 is 1, because 4 goes into 9 twice with a remainder of 1. Modulo
operator can be handy for example when we want to check for prime numbers.
9 ^ 2 = 9 * 9 = 81
Concatenating strings
In Visual Basic we have two operators for string concatenation. The plus + operator and the &
ampersand operator.
Option Strict On
Module Example
Sub Main()
End Sub
End Module
$ ./concatstrings.exe
Return of the king
Return of the king
And this is, what we get. Same result for both cases.
Boolean operators
In Visual Basic, we have the following logical operators. Boolean operators are also called logical.
Symbol Name
Or logical inclusion
Not negation
Module Example
Dim x As Byte = 3
Dim y As Byte = 8
Sub Main()
Console.WriteLine(x = y)
Console.WriteLine(y > x)
If (y > x)
Console.WriteLine("y is greater than x")
End If
End Sub
End Module
Many expressions result in a boolean value. Boolean values are used in conditional statements.
Console.WriteLine(x = y)
Console.WriteLine(y > x)
Relational operators always result in a Boolean value. These two lines print False and True.
If (y > x)
Console.WriteLine("y is greater than x")
End If
The body of the If statement is executed only if the condition inside the parentheses is met. The x
> y returns True, so the message "y is greater than x" is printed to the terminal.
Option Strict On
Module Example
Dim a As Boolean
Dim b As Boolean
Dim c As Boolean
Dim d As Boolean
Sub Main()
Console.WriteLine(a)
Console.WriteLine(b)
Console.WriteLine(c)
Console.WriteLine(d)
End Sub
End Module
Example shows the logical And operator. It evaluates to True only if both operands are True.
$ ./andop.exe
True
False
False
False
The logical Xor operator evaluates to True, if exactly one of the operands is True.
Option Strict On
Module Example
Dim a As Boolean
Dim b As Boolean
Dim c As Boolean
Dim d As Boolean
Sub Main
Console.WriteLine(a)
Console.WriteLine(b)
Console.WriteLine(c)
Console.WriteLine(d)
End Sub
End Module
The logical Xor evaluates to False if both operands are True or both False.
$ ./xorop.exe
False
True
True
False
Option Strict On
Module Example
Sub Main()
Console.WriteLine(a)
Console.WriteLine(b)
Console.WriteLine(c)
Console.WriteLine(d)
End Sub
End Module
If one of the sides of the operator is True, the outcome of the operation is True.
$ ./orop.exe
True
True
True
False
The negation operator Not makes True False and False True.
Option Strict On
Module Example
Sub Main()
Console.WriteLine(Not True)
Console.WriteLine(Not False)
Console.WriteLine(Not (4 < 3))
End Sub
End Module
$ ./negation.exe
False
True
True
AndAlso, OrElse operators are short circuit evaluated. Short circuit evaluation means that the
second argument is only evaluated if the first argument does not suffice to determine the value of
the expression: when the first argument of And evaluates to false, the overall value must be false;
and when the first argument of Or evaluates to true, the overall value must be true. (wikipedia)
Short circuit evaluation is used mainly to improve performance.
Option Strict On
Module Example
Sub Main()
Console.WriteLine("Short circuit")
If (one AndAlso two)
Console.WriteLine("Pass")
End If
Console.WriteLine("#############")
If (one And two)
Console.WriteLine("Pass")
End If
End Sub
End Module
We have two functions in the example. Functions, unlike subroutines, return values. This is the
main difference between them.
If (one AndAlso two)
Console.WriteLine("Pass")
End If
The one function returns False. The short circuit AndAlso does not evaluate the second function. It
is not necessary. Once an operand is False, the result of the logical conclusion is always False.
Only "Inside one" is printed to the console.
Console.WriteLine("#############")
If (one And two)
Console.WriteLine("Pass")
End If
In the second case, we use the And. In this case, both functions are called. Even though it is not
necessary for the result of the expression.
$ ./shorcircuit.exe
Short circuit
Inside one
#############
Inside one
Inside two
Relational operators are used to compare values. These operators always result in a boolean value.
Symbol Meaning
== equal to
Is compares references
As we already mentioned, the relational operators return boolean values. Note that in Visual
Basic, the comparison operator is =. Not == like in C and C influenced languages.
Notice that the relational operators are not limited to numbers. We can use them for other objects
as well. Although they might not always be meaningful.
Option Strict On
Module Example
Sub Main()
End Sub
End Module
We can compare string objects too. Comparison operators in a string context compare the sorting
order of the characters.
Console.WriteLine("a" < "b") ' Prints True
What exactly happens here? Computers do not know characters or strings. For them, everything is
just a number. Characters are special numbers stored in specific tables. Like ASCII.
Option Strict On
Module Example
Sub Main()
End Sub
End Module
Internally, the a and b characters are numbers. So when we compare two characters, we compare
their stored numbers. The built-in Asc function returns the ASCII value of a single character.
$ ./compare.exe
True
a is: 97
b is: 98
Say we have a string with more characters. If the first characters are equal, we compare the next
ones. In our case, the b character at the second position has a greater value than the a character.
That is why "ab" string is greater than "aa" string. Comparing strings in such a way does not make
much sense, of course. But it is technically possible.
Finally, we will mention the Is operator. The operator checks if two object references refer to the
same object. It does not perform value comparisons.
Option Strict On
Module Example
Sub Main()
o3 = o2
Console.WriteLine(o1 Is o2)
Console.WriteLine(o3 Is o2)
End Sub
End Module
We declare and initialise two Object instances. The Object class is a base class for all classes in the
.NET framework. We will describe it later in more detail.
Dim o3 As Object
In the first case, we get False. The o1 and o2 are two different objects. In the second case, we get
True. The o3 and o2 refer to the same object.
Bitwise operators
Decimal numbers are natural to humans. Binary numbers are native to computers. Binary, octal,
decimal, or hexadecimal symbols are only notations of the same number. Bitwise operators work
with bits of a binary number. Bitwise operators are seldom used in higher level languages like
Visual Basic.
Symbol Meaning
Or bitwise or
The operator reverts all bits of a number 7. One of the bits also determines, whether the number is
negative or not. If we negate all the bits one more time, we get number 7 again.
The bitwise and operator performs bit-by-bit comparison between two numbers. The result for a
bit position is 1 only if both corresponding bits in the operands are 1.
00110
And 00011
= 00010
The first number is a binary notation of 6, the second is 3 and the result is 2.
The bitwise or operator performs bit-by-bit comparison between two numbers. The result for a
bit position is 1 if either of the corresponding bits in the operands is 1.
00110
Or 00011
= 00111
The bitwise exclusive or operator performs bit-by-bit comparison between two numbers. The
result for a bit position is 1 if one or the other (but not both) of the corresponding bits in the
operands is 1.
00110
Xor 00011
= 00101
The compound assignment operators consist of two operators. They are shorthand operators.
Option Strict On
Module Example
Dim a As Integer
Sub Main
a = 1
a = a + 1
Console.WriteLine(a) ' Prints 2
a += 1
Console.WriteLine(a) ' Prints 3
End Sub
End Module
The += compound operator is one of these shorthand operators. They are less readable than the
full expressions but experienced programmers often use them.
-= *= \= /= &= ^=
Operator precedence
The operator precedence tells us which operators are evaluated first. The precedence level is
necessary to avoid ambiguity in expressions.
3 + 5 * 5
Like in mathematics, the multiplication operator has a higher precedence than addition operator.
So the outcome is 28.
(3 + 5) * 5
To change the order of evaluation, we can use parentheses. Expressions inside parentheses are
always evaluated first.
The following list shows common Visual Basic operators ordered by precedence (highest
precedence first):
Operator(s) Description
^ exponentiation
\ integer division
Mod modulus
= <> < > >= <= Is IsNot Like TypeOf Is All comparison operators
Not negation
Operators on the same line in the list have the same precedence.
Option Strict On
Module Example
Sub Main()
Console.WriteLine(3 + 5 * 5)
Console.WriteLine((3 + 5) * 5)
End Sub
End Module
In this code example, we show some common expressions. The outcome of each expression is
dependent on the precedence level.
Console.WriteLine(3 + 5 * 5)
This line prints 28. The multiplication operator has a higher precedence than addition. First the
product of 5*5 is calculated. Then 3 is added.
Console.WriteLine(Not True Or True)
In this case, the negation operator has a higher precedence. First, the first True value is negated to
False, than the Or operator combines False and True, which gives True in the end.
$ ./precedence.exe
28
40
True
False
Associativity
Sometimes the precedence is not satisfactory to determine the outcome of an expression. There is
another rule called associativity. The associativity of operators determines the order of evaluation
of operators with the same precedence level.
9 / 3 * 3
What is the outcome of this expression? 9 or 1? The multiplication, deletion and the modulo
operator are left to right associated. So the expression is evaluated this way: (9 / 3) * 3 and the
result is 9.
Arithmetic, boolean, relational and bitwise operators are all left o right associated.
a = b = c = d = 0
Console.WriteLine("{0} {1} {2} {3}", a, b, c, d) ' Prints 0 0 0 0
If the association was left to right, the previous expression would not be possible.
j = 0
j *= 3 + 1
Console.WriteLine(j)
You might expect the result to be 1. But the actual result is 0. Because of the associativity. The
expression on the right is evaluated first and than the compound assignment operator is applied.
AddressOf operator
The AddressOf operator creates a function delegate that points to another function. Delegates are
type safe function pointers, they are used to call methods of other objects.
Option Strict On
Module Example
Sub Main()
msg.Invoke()
msg = New Display(AddressOf Message2)
msg.Invoke()
End Sub
Sub Message1()
Console.WriteLine("This is message 1")
End Sub
Sub Message2()
Console.WriteLine("This is message 2")
End Sub
End Module
In the code example, we use the AddressOf operator to point to two different subroutines.
Delegate Sub Display
The delegate takes the address of a subroutine using the AddressOf operator. Now we have a type-
safe pointer to the Message1() subroutine.
msg.Invoke()
The Invoke() method calls the method, to which the delegate points.
msg = New Display(AddressOf Message2)
msg.Invoke()
$ ./addressof.exe
This is message 1
This is message 2
Introduction
You may want to read some data from an input file and write results into
another output file. In these cases, it is useful to use a plain “text file” (“*.txt”)
which includes no information other than plain text. Files for other software
(e.g., MS Word) contain complicated data that are used to format the
information in the file.
Below is a file containing the names of a few dead rock stars and the dates they
died. You may not have realized that Brian Jones (original rhythm guitarist for
the Rolling Stones) and Jim Morrison died two years apart on the same day.
Access Visual Basic
1. Open VB from the “start” menu, that is:
Start\All Programs\Microsoft Visual Basic
2. Select “File New Project” to create a new project
3. Select “Windows Form Application”. You can give your “application” a
name, or simply accept the default offered “WindowsApplication1”.
Click “OK”.
Prepare the Graphic User Interface
Develop the "form" shown in the figure above that we will use in the project.
The form should contain a label, a text box, two command buttons, and a
picture box with the following properties, and look like:
Lab 4 - CE 311 K - McKinney
2
Add VB Code to the Project
Let’s add some code to the “Stop” button. Double click on the “Stop” button
and type in the following code:
Private Sub Button2_Click(…) Handles Button2.Click
End
End Sub
Double click on the “Go!” button and type in the following code:
Private Sub Button1_Click(…) Handles Button1.Click
Dim sr As IO.StreamReader = IO.File.OpenText("C:\temp\name.txt")
Dim Line, Text(), lastName, firstName, birth As String
Line = sr.ReadLine
Text = Line.Split(" ")
lastName = Text(0)
firstName = Text(1)
birth = Text(2)
ListBox1.Items.Add(firstName & " " & lastName & " " & ", Born: " & birth)
Line = sr.ReadLine
Text = Line.Split(" ")
lastName = Text(0)
firstName = Text(1)
birth = Text(2)
ListBox1.Items.Add(firstName & " " & lastName & " " & ", Born: " & birth)
End Sub
Lab 4 - CE 311 K - McKinney
3
Now, test your code. You should get something that looks like the following.
Let's talk about some of the code here:
Dim sr As IO.StreamReader = IO.File.OpenText("C:\temp\name.txt")
Variable “sr”:
“sr” is declared to be an “IO” object that is capable of receiving input to
your program (it can “read streams” of input).
“sr” is assigned to the “IO” object that points to the file
"C:\temp\name.txt".
Input File Directory Path and Name:
"C:\temp\CE311K\InputOutput\ " is the directory path and “name.txt“ is
the name of the file to be opened. In this example, the path is
“hardcoded” into the program. Be sure that the path is correct for the
location of your file "name.txt".
Dim:
Dim Line, Text(), lastName, firstName, birth As String
The variables “Line”, “Text”, “lastName”, “firstName”, and “birth” are
declared to be “string” variables. “Text” is somewhat special as you can
tell by the parentheses “()” after the name. This means that it is an
“array” variable and can be broken into pieces; we’ll cut it into three
pieces, “Text(0)”, “Text(1)”, and “Text(2)”.
Lab 4 - CE 311 K - McKinney
4
ReadLine:
Line = sr.ReadLine
This line reads one line from the file assigned to the variable “sr” and
assigns that string to the variable “Line”.
Split:
Text = Line.Split(" ")
This line “splits” the variable “Line” into pieces. The splits are made at
locations in the string where the character in the double quotes appear, a
blank space in this case “ “. The pieces are assigned to the variable
“Text”.
Now that we have split the line we read into pieces, we can assign the pieces to
variables:
lastName = Text(0)
firstName = Text(1)
birth = Text(2)
Here we put the first piece “Text(0)” into the variable “lastName”, and so
forth.
Output:
ListBox1.Items.Add(firstName & " " & lastName & " " & ", Born: " & birth)
This adds the indicated output to the listbox “ListBox1”
Lab 4 - CE 311 K - McKinney
5
Write Data to an Output File
Next, let’s write the output to another file.
Private Sub Button1_Click(…) Handles Button1.Click
Dim sr As IO.StreamReader = IO.File.OpenText("C:\temp\name.txt")
Dim sw As IO.StreamWriter = IO.File.CreateText("C:\temp\output.txt")
Dim Line, Text(), lastName, firstName, birth As String
sw.WriteLine("This is the output file.")
Line = sr.ReadLine
Text = Line.Split(" ")
lastName = Text(0)
firstName = Text(1)
birth = Text(2)
ListBox1.Items.Add(firstName & " " & lastName & " " & ", Born: " & birth)
sw.WriteLine(firstName & " " & lastName & " " & ", Born: " & birth)
Line = sr.ReadLine
Text = Line.Split(" "c)
lastName = Text(0)
firstName = Text(1)
birth = Text(2)
ListBox1.Items.Add(firstName & " " & lastName & " " & ", Born: " & birth)
sw.WriteLine(firstName & " " & lastName & " " & ", Born: " & birth)
sw.Close()
End Sub
Let's talk about some of the code here:
Dim sw As IO.StreamWriter = IO.File.CreateText("C:\temp\output.txt")
Variable “sw”:
“sw” is declared to be an “IO” object that is capable of receiving output
from your program (it can “write streams” of output).
“sw” is assigned to the “IO” object that points to the file
"C:\temp\output.txt".
Lab 4 - CE 311 K - McKinney
6
WriteLine:
sw.WriteLine(“This is the output file”)
This line writes one line into the file assigned to the variable “sw”.
sw.WriteLine(firstName & " " & lastName & " " & ", Born: " & birth)
This line writes one line into the output file with the variables indicated.
Close:
sw.Close()
This line closes the output file and allows us to look at the file contents
after the program is stopped.
Lab 4 - CE 311 K - McKinney
7
Assignment
Write a VB code with graphic user interface to find the average annual
temperature in Austin. Use the program “Notebook” to create a text file to use
as input for your program. The input file should contain the information in the
following table: one column for the name of the month and one column for the
temperature of that month. Your program should open the input file and read
it one line at a time and compute the average of the monthly temperatures to
get the annual average temperature. Write the result to an output file.
Month Temperature (deg F)
January 58
February 63
March 71
April 79
May 84
June 91
July 95
August 95
September 90
October 82
November 71
December 62
To be turned in:
You can paste all of the following items into a MS Word document and
print it and hand it in, or email it to me at: [email protected]. Be sure to put
you name on the first line of the document.
1. A printout of he input file from your program.
2. A printout of the VB code used in your program.
Other Versions
Visual Basic lets you test conditions and perform different operations depending
on the results of that test. You can test for a condition being true or false, for
various values of an expression, or for various exceptions generated when you
execute a series of statements.
The following illustration shows a decision structure that tests for a condition
being true and takes different actions depending on whether it is true or false.
If...Then...Else constructions let you test for one or more conditions and run one
or more statements depending on each condition. You can test conditions and
take actions in the following ways:
The control structure that offers all these possibilities is the If...Then...Else
Statement (Visual Basic). You can use a single-line version if you have just one
test and one statement to run. If you have a more complex set of conditions and
actions, you can use the multiple-line version.
Select...Case Construction
The Select...Case construction lets you evaluate an expression one time and run
different sets of statements based on different possible values. For more
information, see Select...Case Statement (Visual Basic).
Try...Catch...Finally Construction
Note
For many control structures, when you click a keyword, all of the keywords in the
structure are highlighted. For instance, when you click If in an If...Then...Else
construction, all instances of If, Then, ElseIf, Else, and End If in the construction
are highlighted. To move to the next or previous highlighted keyword, press
CTRL+SHIFT+DOWN ARROW or CTRL+SHIFT+UP ARROW.
Other Versions
The following illustration shows a loop structure that runs a set of statements until
a condition becomes true.
While Loops
Do Loops
The Do...Loop construction allows you to test a condition at either the beginning
or the end of a loop structure. You can also specify whether to repeat the loop
while the condition remains True or until it becomes True. For more information,
see Do...Loop Statement (Visual Basic).
For Loops
The For...Next construction performs the loop a set number of times. It uses a
loop control variable, also called a counter, to keep track of the repetitions. You
specify the starting and ending values for this counter, and you can optionally
specify the amount by which it increases from one repetition to the next. For
more information, see For...Next Statement (Visual Basic).
The For Each...Next construction runs a set of statements once for each
element in a collection. You specify the loop control variable, but you do not have
to determine starting or ending values for it. For more information, see For
Each...Next Statement (Visual Basic).
Introduction to Arrays
By definition, an array is a list of variables with the same data type and name. When we
work with a single item, we only need to use one variable. However, if we have a list of
items which are of similar type to deal with, we need to declare an array of variables instead
of using a variable for each item
For example, if we need to enter one hundred names, it is difficulty to declare 100 different
names, this is a waste of time and efforts. So, instead of declaring one hundred different
variables, we need to declare only one array. We differentiate each item in the array by
using subscript, the index value of each item, for example name(1), name(2),name(3)
An array stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of
data, but it is often more useful to think of an array as a collection of variables of the same type.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest
address to the last element.
You can also initialize the array elements while declaring the array. For example,
The elements in an array can be stored and accessed by using the index of the array. The following program
demonstrates this:
Module arrayApl
Sub Main()
Dim i, j As Integer
For i = 0 To 10
Next i
' output each array element's value '
For j = 0 To 10
Next j
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
Element(0) = 100
Element(1) = 101
Element(2) = 102
Element(3) = 103
Element(4) = 104
Element(5) = 105
Element(6) = 106
Element(7) = 107
Element(8) = 108
Element(9) = 109
Element(10) = 110
Dynamic Arrays
Dynamic arrays are arrays that can be dimensioned and re-dimensioned as par the need of the program. You can declare
a dynamic array using the ReDim statement.
Where,
The Preserve keyword helps to preserve the data in an existing array, when you resize it.
Module arrayApl
Sub Main()
ReDim marks(2)
marks(0) = 85
marks(1) = 75
marks(2) = 90
marks(3) = 80
marks(4) = 76
marks(5) = 92
marks(6) = 99
marks(7) = 79
marks(8) = 75
For i = 0 To 10
Next i
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
0 85
1 75
2 90
3 80
4 76
5 92
6 99
7 79
8 75
9 0
10 0
Multi-Dimensional Arrays
VB.Net allows multidimensional arrays. Multidimensional arrays are also called rectangular arrays.
Module arrayApl
Sub Main()
Dim a(,) As Integer = {{0, 0}, {1, 2}, {2, 4}, {3, 6}, {4, 8}}
Dim i, j As Integer
For i = 0 To 4
For j = 0 To 1
Next j
Next i
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
a[0,0]: 0
a[0,1]: 0
a[1,0]: 1
a[1,1]: 2
a[2,0]: 2
a[2,1]: 4
a[3,0]: 3
a[3,1]: 6
a[4,0]: 4
a[4,1]: 8
Jagged Array
A Jagged array is an array of arrays. The follwoing code shows declaring a jagged array named scores of Integers:
Module arrayApl
Sub Main()
Dim i, j As Integer
For i = 0 To 4
For j = 0 To 1
Next j
Next i
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
a[0][0]: 0
a[0][1]: 0
a[1][0]: 1
a[1][1]: 2
a[2][0]: 2
a[2][1]: 4
a[3][0]: 3
a[3][1]: 6
a[4][0]: 4
a[4][1]: 8
IsFixedSize
1
Gets a value indicating whether the Array has a fixed size.
IsReadOnly
2
Gets a value indicating whether the Array is read-only.
Length
3
Gets a 32-bit integer that represents the total number of elements in all the dimensions of the Array.
LongLength
4
Gets a 64-bit integer that represents the total number of elements in all the dimensions of the Array.
Rank
5
Gets the rank (number of dimensions) of the Array.
Public Shared Sub Clear (array As Array, index As Integer, length As Integer)
1
Sets a range of elements in the Array to zero, to false, or to null, depending on the element type.
Public Shared Sub Copy (sourceArray As Array, destinationArray As Array, length As Integer)
2 Copies a range of elements from an Array starting at the first element and pastes them into another
Array starting at the first element. The length is specified as a 32-bit integer.
3 Copies all the elements of the current one-dimensional Array to the specified one-dimensional Array
starting at the specified destination Array index. The index is specified as a 32-bit integer.
9 Gets the value at the specified position in the one-dimensional Array. The index is specified as a 32-bit
integer.
10 Searches for the specified object and returns the index of the first occurrence within the entire one-
dimensional Array.
12 Sets a value to the element at the specified position in the one-dimensional Array. The index is specified
as a 32-bit integer.
13 Sorts the elements in an entire one-dimensional Array using the IComparable implementation of each
element of the Array.
For complete list of Array class properties and methods, please consult Microsoft documentation.
Example
The following program demonstrates use of some of the methods of the Array class:
Module arrayApl
Sub Main()
Dim list As Integer() = {34, 72, 13, 44, 25, 30, 10}
Dim temp As Integer() = list
Dim i As Integer
Console.Write("{0} ", i)
Next i
Console.WriteLine()
Array.Reverse(temp)
Console.Write("{0} ", i)
Next i
Console.WriteLine()
Array.Sort(list)
Console.Write("{0} ", i)
Next i
Console.WriteLine()
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
Original Array: 34 72 13 44 25 30 10
Reversed Array: 10 30 25 44 13 72 34
Sorted Array: 10 13 25 30 34 44 72
Unit-4
Types of Procedures
We are going to do something unconventional. Typically a programming language is started
at the basics, like definition of variables and data types. Other elements like
functions/procedures come much later. Here we are going to begin with procedures. VB is
developing into an important tool for designing the Graphical User Interface(GUI) in a window's
application. Event driven procedures are necessary to achieve this. Moreover we would also
like to start fooling with VB.
Procedures allow you to break your programs into discrete logical units, each of which you can
debug more easily than an entire program without procedures.
Procedures used in one program can act as building blocks for other programs, usually with little or
no modification.
Sub Procedure
A Sub procedure is a block of code that is executed in response to an event. By breaking the
code in a module into Sub procedures, it becomes much easier to find or modify the code in
your application.
The syntax for a Sub procedure is: ( we will postpone the discussion on
Private/Public/Static to later)
statements
End Sub
Each time the Sub procedure is called, the statements between Sub and End
Sub are executed. Sub procedures can be placed in standard modules, class
modules, and form modules. Sub procedures are by default Public in all modules,
which means they can be called from anywhere in the application.
The arguments for a procedure are like a variable declaration, declaring values
that are passed in from the calling procedure. We will explore this after we have
defined variables
In VB, it's useful to distinguish between two types of Sub procedures, event
procedures and general procedures.
An event procedure for a form combines the word "Form" an underscore, and
the event name. If you want a form to invoke an event procedure when it is
clicked, use the procedure Form_Click. (Like controls, forms do have unique
names, but they are not used in the names of event procedures.) If you are using
the MDI form, the event procedure combines the word "MDIForm," an
underscore, and the event name, as in MDIForm_Load.
Although you can write event procedures from scratch, it's easier to use the code
procedures provided by VB, which automatically include the correct procedure
names. You can select a template in the Code Editor window by selecting an
object from the Object box and then selecting a procedure from the Procedure
box.
Run the program we have created so far by clicking the blue forward filled triangle on the toolbar
The program compiles and executes. You should see the image of the form with the controls we
created.
Exit/terminate the program by clicking the " X " sign in the title bar of
the application window
This should put us back in VB.
For the following I have retained default names for the various objects on the form. You should
work with the changes you had made earlier because this increases the effectiveness of what
you learn today.
This should place the code view screen in the center area and provide a template for the click
event procedure. This is the mouse click event. We are now ready to write our first event
procedure
We will examine some more aspects of event driven programing. This time we will set up the
first command button to accomplish something for us. We will select the button in a different
way
When the application starts notice that the cursor is in the Textbox. This is the
same as saying that the Textbox has got the focus.
When you click on command1 - two events have simultaneously take place. (1) the Command
Button 1 click event was launched and (2) the Textbox lost focus. The click event of the
command button changed the text in the Textbox and the caption of Label1. The loss of focus
of the Textbox caused a change in the appearance of Label2. Clicking Label1 ( generally not
done - since label basically is a container for descriptive text) causes Label1 to change color -
here a VB constant "vbGreen" is used .
The application should terminate and put us back into VB design environment
General Procedures :
We saw the event procedure respond to an event triggered by the mouse or the cursor. A
general procedure is used to accomplish a specific task. It must be deliberately invoked by the
program. By contrast, an event procedure remains idle until called upon to respond to events
caused by the user or triggered by the system.
One reason to write a general procedure is that is that several different event
procedures might need the same actions performed. A good programming
strategy is to put common statements in a separate procedure (a general
procedure) and have your event procedures call it.
Avoid writing event procedures until you have frozen the Name of the
Object. This allows you to use event procedure templates provided by VB. If
the name is changed after writing the procedures then you will have to change
the name of the procedure too for VB to recognize it as an event procedure. If
VB does not recognize it as an event procedure it is considered a general
procedure.
With Command1
.Left = 50
.Top = Label2.Top + Label2.Height + 50
End With
Command2.Top = Command1.Top
Command2.Left = Command1.Left + Command1.Width + 50
Command2.Height = Command1.Height
Text2.Left = 50
Text2.Top = Command1.Top + Command1.Height + 50
End Sub
Function Procedures
A Function procedure is another kind of procedure, similar to a Sub procedure for it can take
arguments, perform a series of statements, and change the value of its arguments. However,
unlike a Sub procedure, a Function procedure can return a value to the calling procedure.
There are three differences between Sub and Function procedures: (books on
line)
Generally, you call a function by including the function procedure name and arguments on
the right side of a larger statement or expression
returnvalue = function()
Function procedures have data types, just as variables do. This determines
the type of the return value. (In the absence of an As clause, the type is the
default Variant type.)
statements
End Function
Property Procedures
Property procedures are typically use to set an object's property or to get the value of an
object's property. This will be useful when we define our own classes and objects.
Property Set Sets the value of an object property (that is, a property that contains
a reference to an object).
Private: A private global variable can be accessed by any procedure of the same module.
No procedure of another module, even of the same program, can access it
Friend: A friendly global variable can be accessed by any procedure of any module of the
same project. A procedure of another program cannot access that variable
Public: A public global variable can be accessed by any procedure of its project and
procedures of other projects
Based on this characteristic of the procedures of a module having access to global variables of
the same program, you can declare such variables and initialize or modify them in any
procedure of the same code file.
Introduction to Arguments
So far, to use a value in a procedure, we had to declare it. In some cases, a procedure may
need an external value in order to carry its assignment. A value that is supplied to a procedure
is called an argument.
When creating a procedure that will use an external value, declare the argument that represents
that value between the parentheses of the procedure. For a procedure, the syntax you use
would be:
Sub ProcedureName(Argument)
End Sub
Function Sub
The argument must be declared as a normal variable, omitting the Dim keyword. Here is an
example that creates a function that takes a string as argument:
Function Sub
A certain procedure can take more than one argument. In this case, in the parentheses of the
procedure, separate the arguments with a comma. Here is an example of a procedure that takes
two arguments:
End Sub
In the body of a procedure that takes one or more arguments, use the argument(s) as you see
fit as if they were locally declared variables. For example, you can involve them with values
inside of the procedure. You can also exclusively use the values of the arguments to perform the
assignment.
Module Exercise
End Module
As mentioned previously, you can also use the Call keyword to call a procedure.
When you call a procedure that takes more than one argument, you must provide the values of
the arguments in the exact order they are listed inside of the parentheses of the function.
Fortunately, you don't have to. If you know the names of the arguments, you can type them in
any order and provide a value for each. To do that, on the right side of each argument, type the
:= operator followed by the desired value for the argument. Here are examples:
End Module
Practical Learning: Passing Arguments to a Procedure
1. To pass arguments to a function, change the file as follows (when you type the argument,
Microsoft Visual Studio, actually the Visual Basic language parser, will add the ByVal
keywords; in the next sections, we will learn what that keyword means; for now, keep it
but ignore it):
2. Module Geometry
3. Private Function GetValue(TypeOfValue As String) As Double
4. Dim Value As Double
5.
6. Value = InputBox("Enter the " & TypeOfValue & ":")
7. Return Value
8. End Function
9.
10. Private Function CalculatePerimeter(ByVal Length As Double,
11. ByVal Width As Double) As Double
12. CalculatePerimeter = (Length + Width) * 2
13. End Function
14.
15. Public Function Main() As Integer
16. Dim L As Double, W As Double
17. Dim Perimeter As Double
18.
19. L = GetValue("Length")
20. W = GetValue("Width")
21. Perimeter = CalculatePerimeter(L, W)
22.
23. MsgBox("=-= Square Characteristics=-=" & vbCrLf &
24. "Length: " & L & vbCrLf &
25. "Width: " & W & vbCrLf &
26. "Perimeter: " & Perimeter)
27. Return 0
28. End Function
29.
End Module
30. To execute the program, on the main menu, click Debug -> Start Debugging
31. Enter the length as 44.14 and the with as 30.76
32. Close the message box and return to your programming environment
If you create a procedure that takes an argument by value and you have used the ByVal keyword on t
calling the procedure, you don't need to use the ByVal keyword; just the name of the argument is eno
examples on arguments so far. Here is an example:
Welcome(ComputerLanguage)
Return 0
End Function
End Module
Notice that, although the values of the arguments were changed in the Addition() procedure, at the en
they lose the value they got in the function. If you want a procedure to change the value of an argumen
argument by reference.
To pass an argument by reference, on its left, type the ByRef keyword. This is done only when defin
When the procedure finishes with the argument, the argument would keep whatever modification was
Now consider the same program as above but with arguments passed by reference:
Using this technique, you can pass as many arguments by reference and as many arguments by value a
may guess already, this technique is also used to make a procedure return a value, which a regular pr
Furthermore, passing arguments by reference allows a procedure to return as many values as possi
function can return only one value.
41. To execute the program, on the Standard toolbar, click the Start Debugging button
42. Enter the length as 24.55 and the width as 22.85
43. Close the message box and return to your programming environment
Optional Arguments
If you create a procedure that takes one or more arguments, whenever you call that procedure, you m
for the argument(s). Otherwise,, you would receive an error. If such an argument is passed with the sa
over again, you may be tempted to remove the argument altogether. In some cases, although a certain
with the same value most of the time, you still have situations in which you want the user to decide whet
or not for the argument, you can declare the value optional. In other words, you can create the argum
value so that the user can call the procedure without passing a value for the argument, thus passing
necessary. Such an argument is called default or optional.
Imagine you write a procedure that will be used to calculate the final price of an item after discount. Th
need the discount rate in order to perform the calculation. Such a procedure could look like this:
Since this procedure expects an argument, if you do not supply it, the following program would not comp
FinalPrice = CalculateNetPrice(Discount)
End Module
Most of the time, a procedure such as ours would use the same discount rate over and over again. Th
supplying an argument all the time, you can define an argument whose value would be used whenever
provided with the argument.
To specify that an argument is optional, when creating its procedure, type the Optional keyword
argument's name and assign it the default value. Here is an example:
FinalPrice = CalculateNetPrice()
End Module
If a procedure takes more than one argument, you can provide a default argument for each and selec
have default values. If you want all arguments to have default values, when defining the procedure , pr
keyword for each and assign it the desired default value. Here is an example:
Result = "Original Price: " & vbTab & CStr(OrigPrice) & vbCrLf &
"Discount Rate: " & vbTab & CStr(Discount) & "%" & vbCrLf &
"Tax Amount: " & vbTab & CStr(Tax)
MsgBox(Result)
Return NetPrice
End Function
FinalPrice = CalculateNetPrice()
MsgBox("Final Price: " & CStr(FinalPrice))
Return 0
End Function
End Module
If a procedure takes more than one argument as above, remember that some arguments can be speci
this case, when calling the procedure, any argument that does not have a default value must be passed
creating a procedure that takes more than one argument, the argument(s) that has(have) default value(
in the procedure. This means that:
If a procedure takes two arguments and one argument has a default value, this optional argument m
If a procedure is taking three or more arguments and two or more arguments have default values, t
arguments must by placed to the right of the non-optional argument(s).
Because of this, when calling any procedure in the Visual Basic language, you must know what, if any, a
and which one is not.
If a procedure takes two arguments and one argument has a default value, when calling this procedure
one value. In this case, the passed value would be applied on the first argument. If a procedure tak
arguments and two or more arguments have a default value, when calling this procedure, you can provid
of the argument that is (are) not optional. If you want to provide the value of one of the arguments bu
not the first optional, you can leave empty the position(s) of the other argument(s) but remember to
indicate that the position is that of an argument that has a default value. Here is an example:
Result = "Price Acquired: " & vbTab & CStr(AcquiredPrice) & vbCrLf &
"Marked Price: " & vbTab & CStr(MarkedPrice) & vbCrLf &
"Discount Rate: " & vbTab & CStr(DiscountRate) & "%" & vbCrLf &
"Discount Amt: " & vbTab & CStr(DiscountAmount) & vbCrLf &
"Tax Rate: " & vbTab & CStr(TaxRate) & "%" & vbCrLf &
"Tax Amount: " & vbTab & CStr(TaxAmount)
MsgBox(Result)
Return NetPrice
End Function
End Module
Procedure Overloading
A program involves a great deal of names that represent variables and procedures of various kinds. The
allow two variables to have the same name in the same procedure (or in the same scope). Although two
have unique names in the same program, you are allowed to use the same name for different proce
program following certain rules.
The ability to have various procedures with the same name in the same program is referred to as ove
important rule about procedure overloading is to make sure that each one of these procedures has a d
different type(s) of arguments.
1. To start a new project, on the main menu, click File -> New Project...
2. In the middle list, click Console Application
3. Change the Name to MomentOfInertia1
4. Click OK
5. In the Solution Explorer, right-click Module1.vb and click Rename
6. Type MomentOfInertia.vb and press Enter
7. To calculate the moment of inertia of a rectangle, change the file as follows:
8. Module MomentOfInertia
9.
10. ' Moment of Inertia
11. ' Rectangle
12. Private Function MomentOfInertia(ByVal b As Double,
13. ByVal h As Double) As Double
14. Return b * h * h * h / 3
15. End Function
16.
17. Public Sub Main()
18. Dim Base As Double, Height As Double
19.
20. Base = InputBox("Enter the base of the Rectangle")
21. Height = InputBox("Enter the height of the Rectangle")
22.
23. MsgBox("Moment of inertia with regard to the X axis" & vbCrLf &
24. "I = " & CStr(MomentOfInertia(Base, Height)) & "mm")
25. End Sub
26.
End Module
27. To execute the program, on the main menu, click Debug -> Start Debugging
28. Enter the base as 3.25
30. Close the DOS window and return to your programming environment
31. Here are the formulas to calculate the moment of inertia for a semi-circle:
A circle, and thus a semi-circle, requires only a radius. Since the other version
of the MomentOfInertia() function requires two arguments, we can overload it
by providing only one argument, the radius.
32. To calculate the moment of inertia of a rectangle, change the file as follows:
Module MomentOfInertia
' Semi-Circle
Function MomentOfInertia(ByVal R As Double) As Double
Const PI As Double = 3.14159
Return R * R * R * R * PI / 8
End Function
End Module
33. To execute the program, on the Standard toolbar, click the Start Debugging button
34. Enter the radius as 6.35
35. Close the DOS window and return to your programming environment
36. On the main menu, click File -> Close Solution (Microsoft Visual Studio) or File -> Close Project (Mic
2010 Express)
37. When asked whether you want to save, click Discard
Menu bar is the standard feature of most windows applications. The main purpose of the
menus is for easy navigation and control of an application. Some of the most common
menu items are File, Edit, View, Tools, Help and more. Each item on the main menu bar
also provide a list of options or in the form of a pull-down menu. When you create a Visual
Basic 6 program, you need not include as many menu items as a full fledge Windows
application such as Microsoft Words. What you need is to include those menu items that
can improve the ease of using your program by the user, and not to confuse the user with
unnecessary items. Adding menu bar is relatively easy to accomplish in Visual Basic.
There are two ways to add menus to your application, one way is to use the Visual Basic's
Application Wizard and the other way is to use the menu editor.
When you click on the VB Application wizard, the introduction dialog box will appear, as
shown in Figure 37.2. As you are not loading any default setting, just click on the Next
button.
Figure
After clicking the Next button, the interface type dialog box will be displayed, as shown in
There are three choices of interface available for your project. As we currently not creating a
Multiple Document Interface (MDI), we choose Single Document Interface (SDI). You can
also type the project name in the textbox below, here I am using MyFirstMenu.
Clicking the Next button wiill bring up a list of menus and submenus that you can add them
to your application. Check to select a menu item and uncheck to unselect a menu item as
shown in Figure 37.4. Let say we choose all the menus and click next, then you will get an
interface comprises File, Edit, View and Help menus, as shown in Figure 37.5
Figure
you click on any menu item, a list of drop-down submenu items will be displayed. For
example, if you click on the File menu, the list of submenu items such as New, Open, Save,
Save As and more will be displayed, as shown in Figure 37.6
Figure
Clicking on any of the dropped down menu item will show the code associated with it, and
this is where you can modify the code to suit your programming needs. For example,
clicking on the item Open will reveal the following code:
Figure
Now, I will show you how to modify the code in order to open a graphic file and display it in
an image box. For this program, you have to insert a Image box into the form. Next add the
following lines so that the user can open graphic files of different formats.
Then, you need to load the image into the Image box with the following code:
Image1.Picture = LoadPicture(.FileName)
Also set the Stretch property of the Image box to true so that the image loaded can resize
by itself. Please note that each menu item is a special control, so it has a name too. The
name for the menu File in this example is mnuFileOpen.
'ToDo: set the flags and attributes of the common dialog control
.Filter = "Bitmaps(*.BMP)|*.BMP|Metafiles(*.WMF)|*. WMF|Jpeg Files(*.jpg)|*.jpg|GIF
Files(*.gif)|*.gif|Icon Files(*.ico)|*.ico|All Files(*.*)|*.*"
.ShowOpen
Image1.Picture = LoadPicture(.FileName)
If Len(.FileName) = 0 Then
Exit Sub
End If
sFile = .FileName
End With
'ToDo: add code to process the opened file
End Sub
When you run the program and click on the File menu and then the submenu Open, the
following Open dialog box will be displayed, where you can look for graphic files of various
formats to load it into the image box.
Figure
For example, selecting the jpeg file will allow you to choose the images of jpeg format,
Figure
Clicking on the particular picture will load it into the image box,
Figure
To start adding menu items to your application, open an existing project or start a new
project, then click on Tools in the menu bar of the Visual Basic IDE and select Menu Editor.
When you click on the Menu Editor, the Menu Editor dialog will appear. In the Menu Editor
dialog , key in the first item File in the caption text box. You can use the ampersand ( & )
sign in front of F so that F will be underlined when it appears in the menu, and F will
become the hot key to initiate the action under this item by pressing the Alt key and the
letter F. After typing &File in the Caption text box, move to the name textbox to enter the
name for this menu item, you can type in mnuFile here. Now, click the Next button and the
menu item &File will move into the empty space below, as shown in Figure 37.11:
Figure 37.11
You can then add in other menu items on the menu bar by following the same procedure,
Figure
when you click Ok, the menu items will be shown on the menu bar of the form.
Figure
Now, you may proceed to add the sub menus. In the Menu Editor, click on the Insert button
between File and Exit and then click the right arrow key, and the dotted line will appear.
This shows the second level of the menu, or the submenu. Now key in the caption and the
name. Repeat the same procedure to add other submenu items. Here, we are adding New,
Open, Save, Save As and Exit.
Figure
Now click the OK button and go back to your form. You can see the dropped down
submenus when you click on the item File, as shown.
Figure
Finally, you can enter the code by clicking on any of the submenu items.
Simple vb program to dwesign a calculator
Take a few commands and arrange them in calculator style and start executing
the below code with proper command names as specified.
End Sub
End Sub
End Sub
End Sub
End Sub
Private Sub Command7_Click()
Text1.Text = Text1.Text + Command7.Caption
If cleardisplay Then
Text1.Text = ""
cleardisplay = False
End If
End Sub
End Sub