Visual Basic 6 - Hindi Notes PDF
Visual Basic 6 - Hindi Notes PDF
Visual Basic (VB) is a third generation event driven programming language and
associated development environment (IDE) from Microsoft for its COM Programming
model. Visual Basic was derived from BASIC and enables the Rapid Application
Development (RAD) of Graphical User Interface (GUI) applications, access to databases
using DAO(Data access object), RDO(Remote Data Objects), or ADO(ActiveX Data
Objects), and creation of ActiveX controls and object. Scripting languages such as VBA
and VBScript are syntactically similar to Visual Basic, but perform differently.
A programmer can put together an application using the components provided with
Visual Basic itself. Programs written in Visual Basic can also use the Windows API, but
doing so requires external function declarations.
The final release was version 6 in 1998. Microsoft’s extended support ended in
February 2008 and the designated successor was Visual Basic.NET.
VB 1.0 was introduces in 1991. The drag and drop design for creating the user
interface is derived from a prototype form generator developed by Alan Cooper and his
company called Tripod. Microsoft contracted with Alan Cooper and his associates to
develop Tripod into a programmable form system for Windows 3.0, under the code name
Ruby (no relation to the Ruby programming language).
The Ruby interface generator provided the ―visual‖ part of Visual Basic and this
was combined with the ―EB‖ Embedded BASIC engine designed for Microsoft’s
abandoned ―Omega‖ database system. Ruby also provided the ability to load dynamic link
libraries containing additional controls (the called ―gizmos‖) which later became the VBX
interface.
Visual Basic 1.0 for DOS was released in September 1992. The language itself was
not quite compatible with Visual Basic for Windows, as it was actually the next version of
Microsoft’s DOS-based BASIC compilers, QuickBASIC and BASIC Professional
Development System. The interface used the ―COW‖ (Character Oriented Windows)
interface, using extended ASCII characters to simulate the appearance of a GUI.
Visual Basic 2.0 was released in November 1992, the programming environment was easier
to use, and its speed was improved. Notably, forms became instantiable objects, thus laying
the foundational concepts of class modules as were later offered in VB4.
Visual Basic 3.0 was released in the summer of 1993 and came in Standard and
Professional versions. VB3 included version 1.1 of the Microsoft Jet Database Engine
that could read and write Jet (or Access) 1.x databases.
Visual Basic 4.0 (August 1995) was the first version that could create 32-bit as well as 16-
bit Windows programs, It also introduced the ability to write non-GUI classes in Visual
Basic.
With version 5.0 (February 1997), Microsoft released Visual Basic exclusively for 32-bit
versions for Windows, Programmers who preferred to write 16-bit programs were able to
import programs written in visual basic 4.0 to visual basic 5.0 and Visual Basic 5.0
programs can easily be controls, as well as the ability to compiler to native Windows
Executable code, speeding up calculation-intensive code execution. A free, downloadable
Control Creation Edition was also a regular .exe project could be created and run in the
IDE, but not compiled.
Visual Basic 6.0 (Mid 1998) improved in a number of areas including the ability to create
web-based applications. VB6 has entered Microsoft’s ―non-supported phase‖ as of
March 2008.
Mainstream Support for Microsoft Visual Basic 6.0 ended on March 31, 2005. Extended
support ended in March 2008. In response, the Visual Basic User community expressed its
grave concern and lobbied users to sign a petition to keep the product alive. Microsoft has so
far refused to change their position on the matter. Ironically, around the time, it was exposed
that Microsoft’s new anti-spyware offering. Microsoft AntiSpyware (part of GIANT
Company Software purchase), was coded in Visual Basic 6.0.
Microsoft has developed derivatives of Visual Basic for use in scripting. Visual Basic
itself is derived heavily from BASIC, and subsequently has been replaced with a .NET
platform version.
Visual Basic for Application (VBA) is included in many Microsoft applications (Microsoft
Office) and also in many third-party products like AutoCAD, WordPerfect Office 2002 and
ArcGIS. There are small inconsistencies in the away VBA is implemented in different
applications, but it is largely the same language as VB6 and used the same runtime library.
VBScript is the default language for Active Server Pages. It can be used in Windows
scripting and client-side webpage scripting. Although it resembles VB in syntax, it is a
separate language and it is executed by vbscript.dll as opposed to the VB runtime. ASP and
VBScript should not be confused with ASP.NET which used the .Net Framework for
compiled web pages.
Visual Basic.NET is Microsoft’s designated successor to Visual Basic 6.0 and is a part of
Microsoft’s .NET platform. Visual Basic.Net compiles and runs using the .NET framework.
It is not backwards compatible with VB6. An automated conversion tool exists, but for
many projects automated conversion is impossible.
The Visual Basic Learning Edition is the introductory edition that lets you
easily create Windows applications. It comes with al the tools you need to
build mainstream Windows applications.
The Visual Basic Enterprise Edition is the most advanced edition and is
aimed at programmers who build distributed applications in a team
environment. It includes all the features of the Professional edition, plus
tools such as Visual SourceSafe (A version control system) and the
Automation and Component Manager.
You install Visual Basic on your computer using the Setup program. The Setup
program installs Visual Basic and other product components from the CD-ROM to your hard
disc. It also installs the files necessary to view the documentation on the Microsoft Developer
Network CD. If you choose, you can install only the Visual Basic documentation and
samples to your machine.
Important You cannot simply copy files from the CD-ROM to your hard disc and run
Visual Basic. You must use the Setup program, which decompresses and installs the files in
the appropriate directories.
Before you install Visual Basic, make sure that your computer meets the minimum
requirements, and read the Readme file, located at the root directory on your installation disc.
To run Visual Basic, you must have certain hardware and software installed on your
computer. The system requirements include:
For more information please Read the Readme File bundled with Visual Basic 6.0
When you run the Setup program, a directory is created for Visual Basic; you can then
select the components of Visual Basic that you want to install.
With the exception of the operating system files in the \Os directory, files on the
compact disc are not compressed, so they're usable directly from the disc. For example, there
are numerous tools and components in the \Tools directory that can be run or installed
directly from the CD-ROM.
You can run Setup as many times as necessary. For example, you can run Setup to reinstall
Visual Basic in another directory, or to install other portions of Visual Basic.
Think of a window as simply a rectangular region with its own boundaries. You are
probably already aware of several different types of windows: an Explorer window in
Windows, a document window within your word processing program, or a dialog box that
pops up to remind you of an appointment. While these are the most common examples, there
are actually many other types of windows. A command button is a window. Icons, text
boxes, option buttons and menu bars are all windows.
The Microsoft Windows operating system manages all of these many windows by
assigning each one a unique id number (window handle or hWnd). The system continually
monitors each of these windows for signs of activity or events. Events can occur through user
actions such as a mouse click or a key press, through programmatic control, or even as a
result of another window's actions.
Each time an event occurs, it causes a message to be sent to the operating system. The
system processes the message and broadcasts it to the other windows. Each window can then
take the appropriate action based on its own instructions for dealing with that particular
message (for example, repainting itself when it has been uncovered by another window).
As you might imagine, dealing with all of the possible combinations of windows, events and
messages could be mind-boggling. Fortunately, Visual Basic insulates you from having to
deal with all of the low-level message handling. Many of the messages are handled
automatically by Visual Basic; others are exposed as Event procedures for your convenience.
This allows you to quickly create powerful applications without having to deal with
unnecessary details.
Because you can't predict the sequence of events, your code must make certain
assumptions about the "state of the world" when it executes. When you make assumptions
(for example, that an entry field must contain a value before running a procedure to process
that value), you should structure your application in such a way as to make sure that the
assumption will always be valid (for example, disabling the command button that starts the
procedure until the entry field contains a value).
Your code can also trigger events during execution. For example, programmatically
changing the text in a text box cause the text box's Change event to occur. This would cause
the code (if any) contained in the Change event to execute. If you assumed that this event
would only be triggered by user interaction, you might see unexpected results. It is for this
reason that it is important to understand the event-driven model and keep it in mind when
designing your application.
Interactive Development
The traditional application development process can be broken into three distinct
steps: writing, compiling, and testing code. Unlike traditional languages, Visual Basic uses
an interactive approach to development, blurring the distinction between the three steps.
With most languages, if you make a mistake in writing your code, the error is caught
by the compiler when you start to compile your application. You must then find and fix the
error and begin the compile cycle again, repeating the process for each error found. Visual
Basic interprets your code as you enter it, catching and highlighting most syntax or spelling
errors on the fly. It's almost like having an expert watching over your shoulder as you enter
your code.
In addition to catching errors on the fly, Visual Basic also partially compiles the code
as it is entered. When you are ready to run and test your application, there is only a brief
delay to finish compiling. If the compiler finds an error, it is highlighted in your code. You
can fix the error and continue compiling without having to start over.
Because of the interactive nature of Visual Basic, you'll find yourself running your
application frequently as you develop it. This way you can test the effects of your code as
you work rather than waiting to compile later.
2. Select All Programs Microsoft Visual Studio 6.0 Microsoft Visual Basic 6.0.
Note: You can also create a shortcut to Visual Basic, and double-click the shortcut.
Project Explorer
Tool Box
Properties Window
Form Designer Window Standard Tool Bar Form Layout Window
The Visual Basic integrated development environment (IDE) consists of the following
elements.
1 Menu Bar
Displays the commands you use to work with Visual Basic. Besides the standard File, Edit,
View, Window, and Help menus, menus are provided to access functions specific to
programming such as Project, Format, or Debug.
1. File Contains the commands for opening and saving projects and creating executable
files and a list of recent projects.
2. Edit Contains editing commands plus a number of commands for formatting and
editing code.
3. View contains commands for showing or hiding components of the IDE.
4. Project contains commands that add components to the current project, references to
Windows objects, and new tools to the Toolbox.
5. Format contains commands for aligning the controls on the Form.
6. Debug contains the usual debugging commands.
7. Run contains the commands that start, break, and end execution of the current
application.
8. Query contains commands that simplify the design of SQL queries. This menu is
available when building database application.
9. Diagram contains commands for editing database diagrams. This is also available
when building database application.
10. Tools contains tools you need in building ActiveX components and ActiveX controls,
contains the command to start the Menu Editor and the Options command, which lets
you customize the environment.
11. Add-Ins contains add-ins that you can add and remove as needed. By deault, only the
Visual Data Manager Add-In is installed in this menu. Use the Add-In Manager
command to add and remove add-ins.
12. Window is the standard Windows Menu of an application contains commands to
arrange Windows on the screen.
13. Help contains information to help its Users.
2 Context Menus
Contain shortcuts to frequently performed actions. To open a context menu, click the right
mouse button on the object you're using. The specific list of shortcuts available from context
menus depends on the part of the environment where you click the right mouse button. For
example, the context menu displayed when you right click on the Toolbox lets you display
the Components dialog box, hide the Toolbox, dock or undock the Toolbox, or add a custom
tab to the Toolbox.
3 Toolbars
Provide quick access to commonly used commands in the programming environment. You
click a button on the toolbar once to carry out the action represented by that button. By
default, the Standard toolbar is displayed when you start Visual Basic.
Additional toolbars for editing, form design, and debugging can be toggled on or off from the
Toolbars command on the View menu.
Toolbars can be docked beneath the menu bar or can "float" if you select the vertical bar on
the left edge and drag it away from the menu bar.
Standard Toolbar:
The Standard toolbar is just below the menu bar and is displayed by default.
Edit Toolbar:
Debug Toolbar:
The Form Editor toolbar contains the commands of the Format Menu.
Project Explorer Window displays the components of the current project such as Forms,
Modules, Resource File, Data Environment, Data Report Designers etc.
2 3
The Projet Explorer Window has three important
buttons below its title bar.
1
1. View Code:
To view the code editor window of the selected
component.
2. View Object:
To view the Design or Interface of the selected
component. This button would be disable for
the components which has no visible interface.
3. Toggle Folder:
To toggle the listing of the components in explorer style or unarranged.
1 2
5 Toolbox
Provides a set of tools that you use at design time to place controls on a form. In addition to
the default toolbox layout, you can create your own custom layouts by selecting Add Tab
from the context menu and adding controls to the resulting tab.
The Toolbox contains the icons of the controls you can place on a Form to create the
application’s user interface. By default, the Toolbox contains the pointer icons and the icons
of following 20 ActiveX controls.
Pointer:
This control is used to select a control on form and select a range of controls.
Picture Box
This control is used to display images and graphics. It supports many graphical methods
through which graphics can be drawn on it. It also works as a container to other controls. Its
main property is Picture property and to set the picture at run time Load Picture () Method is
used.
Label
This control displays text on a Form that the user can’t edit. Labels commonly identify other
controls and can be transparent, so the text appears to be places directly on the Form. Its
caption property is used to set the text on the label.
Text Box
This control displays the text that the user can edit. The TextBox control is a mini text editor,
and its most important property is the Text property, which can set the text on the control or
read the text that the user enters.
Frame
This control is used to draw container boxes on the Form and used to group other elements.
Its caption property is used to set the text over the title.
Command Button
This is the most common element of the Window s Interface. A Command button represents
an action that is carried out when the user clicks the button. Its Caption property is important
to set the text over the button.
Check Box
The Checkbox Control presents one or more choices that the user can select. The Checkbox
control’s main property is Value, and it is 0 if the Checkbox is cleared and 1 if the Checkbox
is checked. The Checkbox is a toggle. Every item it’s clicked, it changes status (from
checked to cleared and back).
Option Button
Option Buttons, or Radio Buttons, appear in groups, and the user can choose only one of
them. The Option button’s main property is Value, and it is true if the control is checked and
False otherwise. The Option buttons is a toggle. Every time it’s clicked, it changes status
(from checked to cleared and back).
Combo Box
This control is similar to the ListBox Control, but it contains a text Edit field. The user can
either choose an item from the list or enter a new sting in the Edit field. The item selected
from the list (or entered in the Edit field) is given by the control’s Text property.
List Box
The ListBox control contains a list of options from which the user can choose one or more.
unlike a group of Checkboxes or Option buttons, the ListBox control can contain many lines
and the user can scroll the list to locate an item. The selected item in a ListBox control is
given by the Text property. Another important property of the ListBox control is the Sorted
property, which determines whether the items in the list will be sorted.
The horizontal and vertical scrollbars let the user specify a magnitude (the current location in
a long piece of text, a numeric value, and so on) by scrolling the control’s button between its
minimum and maximum value.
Timer
This control can be used to perform tasks at regular intervals. The main property of the Timer
Control is Interval, which determines how often the Timer notifies your application. If the
Interval property is set to 10000, the Timer control issues a Timer event every 10 seconds.
This control displays the drives on the system in a drop-down list from which the user
can select.
This control displays a list of all folders in the current drive and lets the user move up
or down in hierarchy of the folders.
Shape
This control is used to draw graphical elements, such as boxes and circles, on the surface of a
Form.
Line
Similar to Shape Control, the Line Control is used to draw lines on a Form.
Image
This control is similar to the PictureBox control in that it can display images, but it supports
only a few features of the PictureBox control. The drawing of graphics over this control can
not be done like PictureBox control. But it requires fewer resources.
Data
This control provides point-and-click access to data stored in databases. The access, excel
and dbase databases can be directly connected using this control and other controls can be
bounded to this control to access databases and to perform actions on them.
OLE
This control is a window which can be used to place on Form to host documents from other
applications, such as Microsoft Word or Excel. Through this control, a developer can access
the functionality of other applications, if they support OLE.
The Form Designer is the main window in the middle of the screen, and in it you design and
edit the application’s user interface.
It serves as a window that you customize to design the interface of your application. You add
controls, graphics, and pictures to a form to create the look you want. Each form in your
application has its own form designer window.
It serves as an editor for entering application code. A separate code editor window is created
for each form or code module in your application. Module Name
Project Name
Procedure List
Object List
Declaration Area
Procedure
Indication Bar
Procedure Separator
Procedure View
Full Module View
8 Properties Window:
It lists the property settings for the selected form or control. A property is a characteristic of
an object, such as size, caption, or color.
To open the Properties window, choose the Properties Window command from the View
menu, click the Properties Window button on the toolbar, or use the context menu for the
control.
Object Box
Sort Tabs
Properties List
Description Box
The Form Layout window allows us to position the Forms in our application using a small
graphical representation of the screen.
To do this we can move Forms around and place them on top of each other. This window is
useful in applications that use multiple Forms because you can specify how each Form is
positioned with respect to the main Form.
10 Object Browser
It lists objects available for use in your project and gives you a quick way to navigate through
your code. You can use the Object Browser to explore objects in Visual Basic and other
applications, see what methods and properties are available for those objects, and paste code
procedures into your application.
Project/Library List
Search Box
Search Result
Class List
Members List
Description
1. Immediate Window:
It permits ―immediate‖ execution of Visual Basic commands and application
procedures.
2. Locals Window:
It displays the values of variables currently in scope.
3. Watch Window:
It displays the values of the program variables whose values are being watched.
11 Immediate Window
The Immediate window at the bottom of the IDE (if it is not visible, choose View
Immediate Window) is a debugging aid. While an application is running, you can step into
the code and use the Immediate window to examine or change the values of the application’s
variables and to execute Visual Basic commands in Immediate mode. You can also use this
window to execute immediate statements as if it was the window of an advanced calculator
or you can also use variables in the Immediate window.
12 Locals Window:
The Locals window shows the values for any variables, functions and identifiers that are
currently in scope.
13 Watch Window:
To set a watch to a variable just position the cursor within a variable or expression in
the code and then select the Quick Watch command in the Debug Menu.
Or Right Click over the variable or expression and select Add Watch Command from Pop-
Up menu.
Note You can also add features to the Visual Basic interface by using a program called an
add-in. Add-ins, which are available from Microsoft and third-party developers, can provide
features like source code control, which allows you to support group development projects.
Environment Options
Visual Basic provides a great deal of flexibility, allowing you to configure the working
environment to best suit your individual style. You can choose between a single or multiple
document interface, and you can adjust the size and positioning of the various Integrated
Development Environment (IDE) elements. Your layout will persist between sessions of
Visual Basic.
Two different styles are available for the Visual Basic IDE: single document interface (SDI)
or multiple document interface (MDI). With the SDI option, all of the IDE windows are free
to be moved anywhere on screen; as long as Visual Basic is the current application, they will
remain on top of any other applications. With the MDI option, all of the IDE windows are
contained within a single resizable parent
window.
The IDE will start in the selected mode the next time you start Visual Basic.
–or–
Run Visual Basic from the command line with a /sdi or /mdi parameter.
Docking Windows
Many of the windows in the IDE can be docked, or connected, to each other or to the edge of
the screen. These include the Toolbox, Form Layout Window, Project Explorer, Properties
window, Color Palette, and Immediate, Locals, and Watch windows.
With the MDI option, windows can be docked to any side of the parent window; with SDI
they can only be docked beneath the menu bar. Docking capabilities can be toggled on or off
for a given window by selecting the appropriate check box on the Docking tab of the Options
dialog box, available from the Options command on the Tools menu.
2. Drag the window to the desired location by holding down the left mouse button.
Visual Basic applications can be viewed in three distinct states: design, execution and
break.
1. Design State:
In Design State, a programmer can edit the user interface or add code to the
application. All the windows of the IDE and its commands are available to programmer.
2. Execution State:
In Execution State, the application is running. Only a few menu commands are
available and none of the windows of the IDE are available. A programmer can neither edit
the user interface nor add ode to an application while it’s running.
3. Break State:
In Break State, the application’s execution has been interrupted temporarily and can
resume when a programmer press F5 or choose Run Continue. The immediate window is
activated, and programmer can edit the code and issue commands in it. However,
programmers can’t edit the user interface.
Visual Basic IDE offers a couple of project types that a programmer can choose while
opening visual basic IDE. For this Visual Basic IDE displays New Project Dialog Box
(at Start Up) from which programmer can choose a particular type of project. Visual Basic
IDE is configured automatically according to the project type selected and loads the controls
needed into the toolbar to develop that particular type of application.
Visual Basic IDE New Project Dialog Box presents the following 13 types of project
to select-
Standard EXE
These types of projects are available with the Professional Edition; ActiveX components are
OLE automation servers. ActiveX components are basic code-building components that
don’t have a visible interface and that can add special functionality to an application. The two
types of projects are identical in functionality, but are packaged differently (as executable
files or Dynamic Link Libraries).
ActiveX Control
ActiveX documents are in essence Visual Basic applications that can run in the environment
of a container that supports hyperlinking (such as Internet Explorer).
The Application Wizard takes you through the steps of setting up the skeleton of a new
application. The Wizard Manager lets you build your own Wizard. A Wizard is a sequence of
windows that collection information from the user. After the user fills out all the windows,
the Wizard proceeds to build an application, install software, or carry out an automated
operation for the end user.
Data Project
DHTML Application
VB6 allows you to build Dynamic HTML pages that can be displayed in the
browser’s window on a client computer.
IIS Application
VB6 allows you to build applications that run on the Web server and
interact with clients over the Internet with the Internet Information Server.
IIS Applications basically enables the interaction with the server through
a component called Active Server Pages.
AddIn
You can create your own add-ns for the Visual Basic IDE. Add-ins are
special commands you can add to Visual Basic’s menus (they usually
appear) under the Add-Ins menu). To do so, select this type of project.
This is not a new type of project. It simply creates a new Standard EXE
projects and loads all the tools of the Enterprise Edition of Visual Basic.
The Structure of a Visual Basic Project can include following different types of files and
objects.
Form modules (.frm file name extension) can contain textual descriptions of the form and its
controls, including their property settings. They can also contain form-level declarations of
constants, variables, and external procedures; event procedures; and general procedures.
Class modules (.cls file name extension) are similar to form modules, except that they have
no visible user interface. You can use class modules to create your own objects, including
code for methods and properties.
Standard modules (.bas file name extension) can contain public or module-level declarations
of types, constants, variables, external procedures, and public procedures.
Resource files (.res file name extension) contain bitmaps, text strings, and other data that you
can change without having to re-edit your code. For example, if you plan to localize your
application in a foreign language, you can keep all of the user-interface text strings and
bitmaps in a resource file, which you can then localize instead of the entire application. A
project can contain no more than one resource file.
ActiveX documents (.dob) are similar to forms, but are displayable in an Internet browser
such as Internet Explorer. The Professional and Enterprise editions of Visual Basic are
capable of creating ActiveX documents.
User Control (.ctl) and Property Page (.pag) modules are also similar to forms, but are used
to create ActiveX controls and their associated property pages for displaying design-time
properties. The Professional and Enterprise editions of Visual Basic are capable of creating
ActiveX controls.
Additional Components
In addition to files and modules, several other types of components can be added to the
project.
ActiveX controls (.ocx file name extension) are optional controls which can be added to the
toolbox and used on forms. When you install Visual Basic, the files containing the controls
included with Visual Basic are copied to a common directory (the \Windows\System
subdirectory under Windows 95 or later). Additional ActiveX controls are available from a
wide variety of sources. You can also create your own controls using the Professional or
Enterprise editions of Visual Basic.
ActiveX designers are tools for designing classes from which objects can be created. The
design interface for forms is the default designer. Additional designers may be available from
other sources.
3. Insertable Objects
Insertable objects, such as a Microsoft Excel Worksheet object, are components you can use
as building blocks to build integrated solutions. An integrated solution can contain data in
different formats, such as spreadsheets, bitmaps, and text, which were all created by different
applications.
4. References
You can also add references to external ActiveX components that may be used by your
application. You assign references by using the References dialog, accessed from the
References menu item on the Project menu.
Four commands on the File menu allow you to create, open, and save projects.
It is also possible to share files between projects. A single file, such as a form, can be part of
more than one project. Note that changes made to a form or module in one project will be
propagated amongst all projects that share that module.
In the Professional and Enterprise editions of Visual Basic, it is possible to have more than
one project open at a time. This is useful for building and testing solutions involving user-
created controls or other components. When more than one project is loaded, the caption of
the Project Explorer window will change to Project Group and the components of all open
projects will be displayed.
Working with files within a project is similar to working with the projects themselves.
When you add a file to a project, you are simply including a reference to the existing file in
the project; you are not adding a copy of the file. Therefore, if you make changes to a file and
save it, your changes will affect any project that includes the file. To change a file without
affecting other projects, select the file in the Project Explorer, choose Save filename As from
the File menu, and then save the file under a new file name.
Note You can drag and drop files from the Windows Explorer, File Manager, or Network
Neighborhood into the Project window to add them to a project. You can also drag and drop
.ocx files onto the toolbox to add new controls.
3. The file will be removed from the project but not from the disk.
If you remove a file from a project, Visual Basic updates this information in the project file
when you save it. If you delete a file outside of Visual Basic, however, Visual Basic cannot
update the project file; therefore, when you open the project, Visual Basic displays an error
message warning you that a file is missing.
Merging Text
You can also insert existing text from other files into one of your code modules. This is
useful for adding a list of constants or for adding snippets of code that you might have saved
in text files.
1. From the Project window, select the form or module into which you want to insert
code.
2. Choose the View Code button, and move the cursor to the point in the Code Editor
where you want to insert code.
4. Select the name of the text file you want to insert, and choose Open.
Note:
Warning:
If you edit Visual Basic source files using a text or code editor other than Visual Basic, be
careful not to change settings of the attribute VB_PredeclaredId. In particular, changing this
attribute may cause serious problems with the GlobalMultiUse and GlobalSingleUse
classes.
In general, you should not edit attributes manually, as doing so may put the module into an
internally inconsistent state.
The set of controls available in the toolbox can be customized for each project. Any given
control must be in the toolbox before you can add it to a form in the project.
You can add ActiveX controls and insertable objects to your project by adding them to the
toolbox.
1. Right Click on Toolbox and Choose Component from Context Menu Or From the
Project menu, choose Components Or Press Ctrl + T
OR
The Components dialog box is displayed, as shown in Following Figure. The items
listed in this dialog box include all registered ActiveX controls, insertable objects, and
ActiveX designers.
2. To add a control (.ocx file name extension) or an insertable object to the toolbox,
select the check box to the left of the control name.
To view controls with .ocx file name extensions, select the Controls tab. To view
insertable objects, such as a Microsoft Excel Chart, select the Insertable Objects tab.
3. Choose OK to close the Components dialog box. All of the ActiveX controls that you
selected will now appear in the toolbox.
To add ActiveX controls to the Components dialog box, choose the Browse button, and
search other directories for files with a .ocx file name extension. When you add an ActiveX
control to the list of available controls, Visual Basic automatically selects the check box.
Note Each ActiveX control is accompanied by a file with an .ocx extension. This file stores
cached type library information and other data specific to the control. The .ocx files are
typically stored in the same directory as the ActiveX controls and are recreated as needed
(file sizes and dates may change).
2. Clear the check box next to each control you want to remove.
Note:
You cannot remove any control from the toolbox if an instance of that control is used on any
form in the project.
You can also use objects from other applications, such as those included in the Microsoft
Excel object library, either as controls in the toolbox or as programmable objects in your
code.
To make another application's objects available in your code, but not as controls, set a
reference to that application's object library.
2. Select the check box next to each reference you want to add to your project.
To add references to applications not listed in the References dialog box, choose the
Browse button, and then select the application.
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.
Once you have set references to the object libraries you want, you can find a specific object
and its methods and properties in the Object Browser by choosing Object Browser from the
View menu. You can use any object listed in the Object Browser in your code.
A resource file allows you to collect all of the version-specific text and bitmaps for an
application in one place. This can include constant declarations, icons, screen text, and other
material that may change between localized versions or between revisions or specific
configurations.
A single project can have only one resource file; if you add a second file with a .res
extension, an error occurs.
You can make an executable file (.exe) from Visual Basic using the following procedure.
1. From the File menu, choose Make projectname .exe where projectname is the
application name for the project.
2. Type a file name, or browse through the directories and select an existing file name to
overwrite an existing executable with a newer version.
3. By clicking the Options button, you can also specify a number of version-specific
details about the executable file in the Project Properties dialog box.
4. If you want to modify the version number of the project, set the appropriate Major,
Minor, and Revision numbers. Selecting Auto Increment will automatically step the
Revision number each time you run the Make projectname .exe command for this
project.
5. To specify a new name for the application, under Application, type a new name in the
Title box. If you want to specify a new icon, choose one from the list.
6. You can also enter version-specific commentary on a variety of issues under the
Version Information box (comments, company name, trademark and copyright
information, and so on) by selecting a topic from the list box and entering information
in the text box.
7. Choose OK to close the Project Properties dialog box, and then choose OK in the
Make appname .exe dialog box to compile and link the executable file.
You can run the executable file like any other Windows-based application: double-click the
icon for the executable file.
Note Building an executable file from the command line in a DOS session can be useful
when you want to compile a project programmatically. In a batch file, type:
For projectname, type the name of the project file. Use the variable exename to rename the
resulting executable file.
Conditional Compilation
Conditional compilation lets you selectively compile certain parts of the program. You can
include specific features of your program in different versions, such as changing the date and
currency display filters for an application distributed in several different languages.
Visual Basic allows you to customize each project by setting a number of properties. Use the
Project Properties dialog box, accessible through the Project Properties command on the
Project menu. Property settings are saved to the project (.vbp) file.
The following table describes some of the options you can set.
Option Description
Startup Object The first form that Visual Basic displays at run time, or Sub Main ( ).
Project Name Identifies the project in code. It can't contain periods (.), spaces, or
start with a nonalphabetic character. For a public class name, the
project name and class name cannot exceed a total of 37 characters.
Help File The name of the Help file associated with the project.
Project Help The context ID for the specific Help topic to be called when the user
Context ID selects the "?" button while the application's object library is selected
in the Object Browser.
Project Description A user-friendly name for the project. Displayed in the References
and Object Browser dialog boxes.
Note:
Many other options are also available, including those for compiling, components, and
multithreading. When you're ready to access some of the more advanced options, you can
find more information by searching MSDN Help or Online on Microsoft MSDN Website.
Visual Basic allows you to select and manage add-ins, which are extensions to Visual Basic.
These extensions add capabilities to the Visual Basic development environment, for example,
special source code control capabilities.
Microsoft and other developers have created add-ins you can use in your applications.
Wizards are a type of add-in that can simplify certain tasks, such as creating a form. Several
wizards are included in Visual Basic.
To have an add-in appear on the Add-In Manager dialog box, the developer of the add-in
must ensure that it is installed properly.
You can add or remove an add-in to your project by using the Add-In Manager, which is
accessible from the Add-Ins menu. The Add-In Manager dialog box lists the available add-
ins.
To install an add-in
2. Highlight an add-in from the list and click the desired behaviors in Load Behavior. To
unload an add-in or prevent it from loading, clear all Load Behavior boxes.
Depending upon your Load Behavior selections, Visual Basic connects the selected
add-ins and disconnects the
cleared add-ins.
Using Wizards:
Wizards make working with Visual Basic even easier by providing task-specific assistance.
For example, the Application Wizard included in Visual Basic helps you to create the
framework for an application by presenting a series of questions or choices. It generates the
forms and the code behind the forms based on your choices; all you need to do is add code
for your own specific functionality.
The Professional and Enterprise editions of Visual Basic include other wizards, including a
Data Form Wizard for creating forms to be used with databases, and an ActiveX Document
Wizard for converting forms for use in Internet applications.
Wizards are installed or removed using the Add-in Manager. Once installed, they will appear
as selections on the Add-Ins menu. Some of the wizards also appear as icons in the related
dialog boxes; for example, the Application Wizard can also be accessed using its icon in the
New Project dialog box.
–or–
An application is really nothing more than a set of instructions directing the computer to
perform a task or tasks. The structure of an application is the way in which the instructions
are organized; that is, where the instructions are stored and the order in which instructions are
executed.
Simple applications such as the classic "hello world" example have a simple structure;
organization isn't very important with a single line of code. As applications become more
complex, the need for organization or structure becomes obvious. Imagine the confusion that
would result if your application's code was allowed to execute in random order. In addition to
controlling the execution of an application, the structure is important to the programmer: how
easily can you find specific instructions within your application?
Because a Visual Basic application is based on objects, the structure of its code closely
models its physical representation on screen. By definition, objects contain data and code.
The form that you see on screen is a representation of the properties that define its
appearance and intrinsic behavior. For each form in an application, there is a related form
module (with file name extension .frm) that contains its code.
Each form module contains event procedures — sections of code where you place the
instructions that will execute in response to specific events. Forms can contain controls. For
each control on a form, there is a corresponding set of event procedures in the form module.
In addition to event procedures, form modules can contain general procedures that are
executed in response to a call from any event procedure.
Code that isn't related to a specific form or control can be placed in a different type of
module, a standard module (.BAS). A procedure that might be used in response to events in
several different objects should be placed in a standard module, rather than duplicating the
code in the event procedures for each object.
A class module (.CLS) is used to create objects that can be called from procedures within
your application. Whereas a standard module contains only code, a class module contains
both code and data — you can think of it as a control without a physical representation.
The types of events recognized by an object vary, but many types are common to most
controls. For example, most objects recognize a Click event — if a user clicks a form, code
in the form's Click event procedure is executed; if a user clicks a command button, code in
the button's Click event procedure is executed. The actual code in each case will most likely
be quite different.
2. The form (or a control on the form) receives an event. The event might be caused by
the user (for example, a keystroke), by the system (for example, a timer event), or
indirectly by your code (for example, a Load event when your code loads a form).
Note Many events occur in conjunction with other events. For example, when the DblClick
event occurs, the MouseDown, MouseUp, and Click events also occur.
Before you begin, it's important to understand the mechanics of writing code in Visual Basic.
Like any programming language, Visual Basic has its own rules for organizing, editing, and
formatting code.
The following topics introduce code modules and procedures; discuss the basics of using the
Code Editor, and cover basic rules for writing code.
Code Modules
An introduction to the different types of code modules and the procedures that they
contain.
Code Basics
Code Modules
Code in Visual Basic is stored in modules. There are three kinds of modules: form, standard,
and class.
Simple applications can consist of just a single form, and all of the code in the application
resides in that form module. As your applications get larger and more sophisticated, you add
additional forms. Eventually you might find that there is common code you want to execute
in several forms. You don't want to duplicate the code in both forms, so you create a separate
module containing a procedure that implements the common code. This separate module
should be a standard module. Over time, you can build up a library of modules containing
shared procedures.
Declarations. You can place constant, type, variable, and dynamic-link library (DLL)
procedure declarations at the module level of form, class or standard modules.
Procedures. A Sub, Function, or Property procedure contains pieces of code that can
be executed as a unit.
Form Modules
Form modules (.FRM file name extension) are the foundation of most Visual Basic
applications. They can contain procedures that handle events, general procedures, and form-
level declarations of variables, constants, types, and external procedures. If you were to look
at a form module in a text editor, you would also see descriptions of the form and its controls,
including their property settings. The code that you write in a form module is specific to the
particular application to which the form belongs; it might also reference other forms or
objects within that application.
Standard Modules
Standard modules (.BAS file name extension) are containers for procedures and declarations
commonly accessed by other modules within the application. They can contain global
(available to the whole application) or module-level declarations of variables, constants,
types, external procedures, and global procedures. The code that you write in a standard
module isn't necessarily tied to a particular application; if you're careful not to reference
forms or controls by name, a standard module can be reused in many different applications.
Class Modules
Class modules (.CLS file name extension) are the foundation of object-oriented programming
in Visual Basic. You can write code in class modules to create new objects. These new
objects can include your own customized properties and methods. Actually, forms are just
class modules that can have controls placed on them and can display form windows.
Note The Professional and Enterprise editions of Visual Basic also include ActiveX
Documents, ActiveX Designers, and User Controls. These introduce new types of modules
with different file name extensions. From the standpoint of writing code, these modules
should be considered the same as form modules.
The Visual Basic Code Editor is a window where you write most of your code. It is like a
highly specialized word processor with a number of features that make writing Visual Basic
code a lot easier.
Object List
Declaration
Area
Procedure
Separator
Indication
Bar
Procedure
View
Full Module View
Button
Because you work with Visual Basic code in modules, a separate Code Editor window is
opened for each module you select from the Project Explorer. Code within each module is
subdivided into separate sections for each object contained in the module. Switching between
sections is accomplished using the Object Listbox. In a form module, the list includes a
general section, a section for the form itself, and a section for each control contained on the
form. For a class module, the list includes a general section and a class section; for a standard
module only a general section is shown.
Each section of code can contain several different procedures, accessed using the Procedure
Listbox. The procedure list for a form module contains a separate section for each event
procedure for the form or control. For example, the procedure list for a Label control
includes sections for the Change, Click, and DblClick events, among others. Class modules
list only the event procedures for the class itself — Initialize and Terminate. Standard
modules don't list any event procedures, because a standard module doesn't support events.
The procedure list for a general section of a module contains a single selection — the
Declarations section, where you place module-level variable, constant, and DLL declarations.
As you add Sub or Function procedures to a module, those procedures are added in the
Procedure Listbox below the Declarations section.
Two different views of your code are available in the Code Editor window. You can choose
to view a single procedure at a time, or to view all of the procedures in the module with each
procedure separated from the next by a line (as shown in Figure 5.4). To switch between the
two views, use the View Selection buttons in the lower left-hand corner of the editor
window.
Object List Procedure List
Comments
Procedure
Visual Basic makes writing code much easier with features that can automatically fill in
statements, properties, and arguments for you. As you enter code, the editor displays lists of
appropriate choices, statement or function prototypes, or values. Options for enabling or
disabling these and other code settings are available on the Editor tab of the Options dialog,
accessed through the Options command on the Tools menu.
When you enter the name of a control in your code, the Auto List Members feature presents a
drop-down list of properties available for that control. Type in the first few letters of the
property name and the name will be selected from the list; the TAB key will complete the
typing for you. This option is also helpful when you aren't sure which properties are available
for a given control. Even if you choose to disable the Auto List Members feature, you can
still access it with the CTRL+J key combination.
The Auto Quick Info feature displays the syntax for statements and functions. When you
enter the name of a valid Visual Basic statement or function the syntax is shown immediately
below the current line, with the first argument in bold. After you enter the first argument
value, the second argument appears in bold. Auto Quick Info can also be accessed with the
CTRL+I key combination.
Bookmarks
Bookmarks can be used to mark lines of code in the Code Editor so that you can easily return
to them later. Commands to toggle bookmarks on or off as well as to navigate existing
bookmarks are available from the Edit, Bookmarks menu item, or from the Edit toolbar
Code Basics:
This section presents information on code writing mechanics, including breaking and
combining lines of code, adding comments to your code, using numbers in code, and
following naming conventions in Visual Basic.
You can break a long statement into multiple lines in the Code window using the line-
continuation character (a space followed by an underscore). Using this character can make
your code easier to read, both online and when printed. The following code is broken into
three lines with line-continuation characters ( _ ):
Data1.RecordSource = _
"SELECT * FROM Titles, Publishers" _
& "WHERE Publishers.PubId = Titles.PubID" _
& "AND Publishers.State = 'CA'"
You can't follow a line-continuation character with a comment on the same line. There are
also some limitations as to where the line-continuation character can be used.
There is usually one Visual Basic statement to a line, and there is no statement terminator.
However, you can place two or more statements on a line if you use a colon (:) to separate
them:
In order to make your code more readable, however, it's better to place each statement on a
separate line.
As you read through the examples in this guide, you'll often come across the comment
symbol ( ' ). This symbol tells Visual Basic to ignore the words that follow it. Such words are
remarks placed in the code for the benefit of the developer, and other programmers who
might examine the code later. For example:
Comments can follow a statement on the same line or can occupy an entire line. Both are
illustrated in the preceding code. Remember that comments can't follow a line-continuation
character on the same line.
Note
You can add or remove comment symbols for a block of code by selecting two or more lines
of code and choosing the Comment Block or Uncomment Block buttons on the Edit toolbar.
While you are writing Visual Basic code, you declare and name many elements (Sub and
Function procedures, variables, constants, and so on). The names of the procedures,
variables, and constants that you declare in your Visual Basic code must follow these
guidelines:
They can be no longer than 255 characters. The names of controls, forms, classes, and
modules must not exceed 40 characters.
A restricted keyword is a word that Visual Basic uses as part of its language. This includes
predefined statements (such as If and Loop), functions (such as Len and Abs), and operators
(such as Or and Mod).
Your forms and controls can have the same name as a restricted keyword. For example, you
can have a control named Loop. In your code you cannot refer to that control in the usual
way, however, because Visual Basic assumes you mean the Loop keyword. For example, this
code causes an error:
To refer to a form or control that has the same name as a restricted keyword, you must either
qualify it or surround it with square brackets: [ ]. For example, this code does not cause an
error:
You can use square brackets in this way when referring to forms and controls, but not when
declaring a variable or defining a procedure with the same name as a restricted keyword.
Square brackets can also be used to force Visual Basic to accept names provided by other
type libraries that conflict with restricted keywords.
Note
Because typing square brackets can get tedious, you might want to refrain from using
restricted keywords as the name of forms and controls.
This chapter describes the system requirements, limitations on a Visual Basic project, the
types of files that may be included in your Visual Basic project, and descriptions of the form
(.frm) and project (.vbp) files.
Note While many of these limitations are described in terms of a specific number, keep in
mind that other conditions (such as available memory and system resources) may impose a
restriction before the specified limit is reached.
Topics
2. Project Limitations
Limitations that restrict how you will write code, how many controls you can
use in an application, or how data input is managed.
Design- and run-time files that may be included in your Visual Basic project.
4. Form Structures
The following hardware and software is required for Visual Basic applications:
Microsoft Internet Explorer version 4.01 or later (version 4.01 Service Pack 1 or later
for DHTML application developers, and 4.x for end-users of these applications).
o Enterprise Edition: typical installation 128 MB, full installation 147 MB.
Project Limitations
A single project can contain up to 32,000 "identifiers" (any nonreserved keyword), which
include, but are not limited to, forms, controls, modules, variables, constants, procedures,
functions, and objects. Note that the actual number of identifiers is limited to available
memory.
Variable names in Visual Basic can be no longer than 255 characters, and the names of
forms, controls, modules, and classes cannot be longer than 40 characters. Visual Basic
imposes no limit on the actual number of distinct objects in a project.
Microsoft Visual Basic utilizes and creates a number of files at both design and run time.
Which files will be required by your project or application depends upon its scope and
functionality.
Visual Basic produces a number of files when you create and compile a project. These can be
categorized as follows: design-time, miscellaneous development, and run-time.
Design time files are the building blocks of your project: basic modules (.bas) and form
modules (.frm), for example.
Miscellaneous files are produced by various processes and functions of the Visual Basic
development environment: Package and Deployment Wizard dependency files (.dep), for
example.
The following table lists all the design-time and miscellaneous other files that may be
produced when you develop an application:
Extension Description
.bas Basic module
.cls Class module
.ctl User Control file
.ctx User Control binary file
.dca Active Designer cache
.ddf Package and Deployment Wizard CAB information file
.dep Package and Deployment Wizard dependency file
.dob ActiveX document form file
.dox ActiveX document binary form file
.dsr Active Designer file
.dsx Active Designer binary file
.dws Deployment wizard script file
.frm Form file
.frx Binary form file
.log Log file for load errors
.oca Control TypeLib cache file
.pag Property page file
.pgx Binary property page file
.res Resource file
Run-Time Files
When you compile your application, all the necessary design-time files are included in the
run-time executable files. Run-time files are listed in the following table:
Extension Description
.dll In-process ActiveX component
.exe Executable file or ActiveX component
.ocx ActiveX control
.vbd ActiveX document state file
.wct WebClass HTML template
Form Structures
While many of the files in a typical Visual Basic project are in a binary format and are
readable only by specific processes and functions of Visual Basic or your application, the
form (.frm) and project (.vbp) files are saved as ASCII text. These are readable in a text
viewer (Notepad for instance).
The following sections describe the design- and run-time files in a typical Visual Basic
project and the format of the form (.frm) and project (.vbp) files.
Visual Basic form (.frm) files are created and saved in ASCII format. The structure of a form
consists of:
The form description contains the property settings of the form. Blocks of text that define the
properties of controls on the form are nested within the form. Controls contained within other
controls have their properties nested within the text of the container. Following Figure
illustrates the structure of the form description.
If you want to print a form description, you can do so without having to save the form.
2. Select the Form As Text check box, and choose OK to print the form description.
You often need to store values temporarily when performing calculations with Visual Basic.
For example, you might want to calculate several values, compare them, and perform
different operations on them, depending on the result of the comparison. You need to retain
the values if you want to compare them, but you don't need to store them in a property.
Visual Basic, like most programming languages, uses variables for storing values. Variables
have a name (the word you use to refer to the value the variable contains) and a data type
(which determines the kind of data the variable can store). Arrays can be used to store
indexed collections of related variables.
Constants also store values, but as the name implies, those values remain constant
throughout the execution of an application. Using constants can make your code more
readable by providing meaningful names instead of numbers. There are a number of built-in
constants in Visual Basic, but you can also create your own.
Data types control the internal storage of data in Visual Basic. By default, Visual Basic uses
the Variant data type. There are a number of other available data types that allow you to
optimize your code for speed and size when you don't need the flexibility that Variant
provides.
Variables
An introduction to variables: what they are and how to use them.
Static Variables
An introduction to using static variables to preserve values.
Constants
An introduction to using constants to represent values.
Data Types
A discussion of the data types available in Visual Basic.
Arrays
An introduction to the use of arrays for groups of values.
Dynamic Arrays
A discussion of using dynamic arrays to work with groups of values.
Variables:
In Visual Basic, you use variables to temporarily store values during the execution of an
application. Variables have a name (the word you use to refer to the value the variable
contains) and a data type (which determines the kind of data the variable can store).
You can think of a variable as a placeholder in memory for an unknown value. For example,
imagine you are creating a program for a fruit stand to track the sales of apples. You don't
know the price of an apple or the quantity sold until the sale actually occurs. You can use two
variables to hold the unknown values — let's name them ApplePrice and ApplesSold. Each
time the program is run, the user supplies the values for the two variables. To calculate the
total sales and display it in a Textbox named txtSales, your code would look like this:
The expression returns a different total each time, depending on what values the user
provides. The variables allow you to make a calculation without having to know in advance
what the actual inputs are.
In this example, the data type of ApplePrice is Currency; the data type of ApplesSold is an
integer. Variables can represent many other values as well: text values, dates, various
numeric types, even objects.
You use assignment statements to perform calculations and assign the result to a variable:
Note that the equal sign in this example is an assignment operator, not an equality operator;
the value (10) is being assigned to the variable (ApplesSold).
Declaring Variables
To declare a variable is to tell the program about it in advance. You declare a variable with
the Dim statement, supplying a name for the variable:
Variables declared with the Dim statement within a procedure exist only as long as the
procedure is executing. When the procedure finishes, the value of the variable disappears.
In addition, the value of a variable in a procedure is local to that procedure — that is, you
can't access a variable in one procedure from another procedure. These characteristics allow
you to use the same variable names in different procedures without worrying about conflicts
or accidental changes.
A variable name:
Must be unique within the same scope, which is the range from which the variable can
be referenced — a procedure, a form, and so on.
The optional As type clause in the Dim statement allows you to define the data type or object
type of the variable you are declaring. Data types define the type of information the variable
stores. Some examples of data types include String, Integer, and Currency. Variables can also
contain objects from Visual Basic or other applications. Examples of Visual Basic object
types, or classes, include Object, Form1, and TextBox.
Declaring a variable using the Public keyword makes it available throughout your
application.(Global Variables)
Declaring a local variable using the Static keyword preserves its value even when a
procedure ends. (Local Variables)
1. Implicit Declaration
2. Explicit Declaration
Implicit Declaration
You don't have to declare a variable before using it. For example, you could write a function
where you don't need to declare TempVal before using it:
Function SafeSqr(num)
TempVal = Abs(num)
SafeSqr = Sqr(TempVal)
End Function
Visual Basic automatically creates a variable with that name, which you can use as if you had
explicitly declared it. While this is convenient, it can lead to subtle errors in your code if you
misspell a variable name. For example, suppose that this was the function you wrote:
Function SafeSqr(num)
TempVal = Abs(num)
SafeSqr = Sqr(TemVal)
End Function
At first glance, this looks the same. But because the TempVal variable was misspelled on the
next-to-last line, this function will always return zero. When Visual Basic encounters a new
name, it can't determine whether you actually meant to implicitly declare a new variable or
you just misspelled an existing variable name, so it creates a new variable with that name.
Explicit Declaration
To avoid the problem of misnaming variables, you can stipulate that Visual Basic always
warn you whenever it encounters a name not declared explicitly as a variable.
Place this statement in the Declarations section of a class, form, or standard module:
Option Explicit
–or–
From the Tools menu, choose Options, click the Editor tab and check the Require
Variable Declaration option. This automatically inserts the Option Explicit statement
in any new modules, but not in modules already created; therefore, you must manually
add Option Explicit to any existing modules within a project.
Had this statement been in effect for the form or standard module containing the SafeSqr
function, Visual Basic would have recognized TempVal and TemVal as undeclared variables
and generated errors for both of them. You could then explicitly declare TempVal:
Function SafeSqr(num)
Dim TempVal
TempVal = Abs(num)
SafeSqr = Sqr(TemVal)
End Function
Now you'd understand the problem immediately because Visual Basic would display an error
message for the incorrectly spelled TemVal. Because the Option Explicit statement helps
you catch these kinds of errors, it's a good idea to use it with all your code.
Note :
The Option Explicit statement operates on a per-module basis; it must be placed in the
Declarations section of every form, standard, and class module for which you want Visual
Basic to enforce explicit variable declarations. If you select Require Variable Declaration,
Visual Basic inserts Option Explicit in all subsequent form, standard, and class modules, but
does not add it to existing code. You must manually add Option Explicit to any existing
modules within a project.
The scope of a variable defines which parts of your code are aware of its existence. When
you declare a variable within a procedure, only code within that procedure can access or
change the value of that variable; it has a scope that is local to that procedure. Sometimes,
however, you need to use a variable with a broader scope, such as one whose value is
available to all the procedures within the same module, or even to all the procedures in your
entire application. Visual Basic allows you to specify the scope of a variable when you
declare it.
Scoping Variables
Procedure-level variables are recognized only in the procedure in which they're declared.
These are also known as local variables. You declare them with the Dim or Static keywords.
For example:
–or–
Values in local variables declared with Static exist the entire time your application is running
while variables declared with Dim exist only as long as the procedure is executing.
Local variables are a good choice for any kind of temporary calculation. For example, you
can create a dozen different procedures containing a variable called intTemp. As long as each
intTemp is declared as a local variable, each procedure recognizes only its own version of
intTemp. Any one procedure can alter the value in its local intTemp without affecting
intTemp variables in other procedures.
By default, a module-level variable is available to all the procedures in that module, but not
to code in other modules. You create module-level variables by declaring them with the
Private keyword in the Declarations section at the top of the module. For example:
At the module level, there is no difference between Private and Dim, but Private is preferred
because it readily contrasts with Public and makes your code easier to understand.
To make a module-level variable available to other modules, use the Public keyword to
declare the variable. The values in public variables are available to all procedures in your
application. Like all module-level variables, public variables are declared in the Declarations
section at the top of the module. For example:
Note You can't declare public variables within a procedure, only within the Declarations
section of a module.
Static Variables
In addition to scope, variables have a lifetime, the period of time during which they retain
their value. The values in module-level and public variables are preserved for the lifetime of
your application. However, local variables declared with Dim exist only while the procedure
in which they are declared is executing. Usually, when a procedure is finished executing, the
values of its local variables are not preserved and the memory used by the local variables is
reclaimed. The next time the procedure is executed, all its local variables are reinitialized.
However, you can preserve the value of a local variable by making the variable static. Use
the Static keyword to declare one or more variables inside a procedure, exactly as you would
with the Dim statement:
Static Depth
For example, the following function calculates a running total by adding a new value to the
total of previous values stored in the static variable Accumulate:
Function RunningTotal(num)
Static ApplesSold
ApplesSold = ApplesSold + num
RunningTotal = ApplesSold
End Function
If ApplesSold was declared with Dim instead of Static, the previous accumulated values
would not be preserved across calls to the function, and the function would simply return the
same value with which it was called.
You can produce the same result by declaring ApplesSold in the Declarations section of the
module, making it a module-level variable. Once you change the scope of a variable this
way, however, the procedure no longer has exclusive access to it. Because other procedures
can access and change the value of the variable, the running totals might be unreliable and
the code would be more difficult to maintain.
To make all local variables in a procedure static, place the Static keyword at the beginning of
a procedure heading. For example:
This makes all the local variables in the procedure static regardless of whether they are
declared with Static, Dim, Private, or declared implicitly. You can place Static in front of any
Sub or Function procedure heading, including event procedures and those declared as
Private.
Constants:
Often you'll find that your code contains constant values that reappear over and over. Or you
may find that the code depends on certain numbers that are difficult to remember — numbers
that, in and of themselves, have no obvious meaning.
In these cases, you can greatly improve the readability of your code — and make it easier to
maintain — by using constants. A constant is a meaningful name that takes the place of a
number or string that does not change. Although a constant somewhat resembles a variable,
you can't modify a constant or assign a new value to it as you can to a variable. There are two
sources for constants:
Symbolic or user-defined constants are declared using the Const statement. User-
defined constants are described in the next section, "Creating Your Own Constants."
In Visual Basic, constant names are in a mixed-case format, with a prefix indicating the
object library that defines the constant. Constants from the Visual Basic and Visual Basic for
applications object libraries are prefaced with "vb" — for instance, vbTileHorizontal.
The prefixes are intended to prevent accidental collisions in cases where constants have
identical names and represent different values. Even with prefixes, it's still possible that two
object libraries may contain identical constants representing different values. Which constant
is referenced in this case depends on which object library has the higher priority
To be absolutely sure you avoid constant name collisions, you can qualify references to
constants with the following syntax:
[libname.][modulename.]constname
Libname is usually the class name of the control or library. Modulename is the name of the
module that defines the constant. Constname is the name of the constant. Each of these
elements is defined in the object library, and can be viewed in the Object Browser.
The argument constantname is a valid symbolic name (the rules are the same as those for
creating variable names), and expression is composed of numeric or string constants and
operators; however, you can't use function calls in expression.
You can place more than one constant declaration on a single line if you separate them with
commas:
The expression on the right side of the equal sign ( = ) is often a number or literal string, but
it can also be an expression that results in a number or string (although that expression can't
contain calls to functions). You can even define constants in terms of previously defined
constants:
Once you define constants, you can place them in your code to make it more readable. For
example:
Data Types
Variables are placeholders used to store values; they have names and data types. The data
type of a variable determines how the bits representing those values are stored in the
computer's memory. When you declare a variable, you can also supply a data type for it. All
variables have a data type that determines what kind of data they can store.
By default, if you don't supply a data type, the variable is given the Variant data type. The
Variant data type is like a chameleon — it can represent many different data types in
different situations. You don't have to convert between these types of data when assigning
them to a Variant variable: Visual Basic automatically performs any necessary conversion.
If you know that a variable will always store data of a particular type, however, Visual Basic
can handle that data more efficiently if you declare a variable of that type. For example, a
variable to store a person's name is best represented as a string data type, because a name is
always composed of characters.
Data types apply to other things besides variables. When you assign a value to a property,
that value has a data type; arguments to functions also have data types. In fact, just about
anything in Visual Basic that involves data also involves data types.
Before using a non-Variant variable, you must use the Private, Public, Dim or Static
statement to declare it As type. For example, the following statements declare an Integer,
Double, String, and Currency type, respectively:
Private I As Integer
Dim Amt As Double
Static YourName As String
Public BillsPaid As Currency
Note If you do not supply a data type, the variable is given the default type. In the preceding
example, the variables Test and Amount are of the Variant data type. This may surprise you
if your experience with other programming languages leads you to expect all variables in the
same declaration statement to have the same specified type (in this case, Integer).
Visual Basic supplies several numeric data types — Integer, Long (long integer), Single
(single-precision floating point), Double (double-precision floating point), and Currency.
Using a numeric data type generally uses less storage space than a variant.
If you know that a variable will always store whole numbers (such as 12) rather than
numbers with a fractional amount (such as 3.57), declare it as an Integer or Long type.
Operations are faster with integers, and these types consume less memory than other data
types. They are especially useful as the counter variables in For...Next loops.
If the variable contains a fraction, declare it as a Single, Double, or Currency variable. The
Currency data type supports up to four digits to the right of the decimal separator and fifteen
digits to the left; it is an accurate fixed-point data type suitable for monetary calculations.
Floating-point (Single and Double) numbers have much larger ranges than Currency, but can
be subject to small rounding errors.
If the variable contains binary data, declare it as an array of the Byte data type. (Arrays are
discussed in "Arrays" later in this chapter). Using Byte variables to store binary data
preserves it during format conversions. When String variables are converted between ANSI
and Unicode formats, any binary data in the variable is corrupted. Visual Basic may
automatically convert between ANSI and Unicode when:
Writing to files
Calling DLLs
All operators that work on integers work with the Byte data type except unary minus. Since
Byte is an unsigned type with the range 0-255, it cannot represent a negative number. So for
unary minus, Visual Basic coerces the Byte to a signed integer first.
All numeric variables can be assigned to each other and to variables of the Variant type.
Visual Basic rounds off rather than truncates the fractional part of a floating-point number
before assigning it to an integer.
If you have a variable that will always contain a string and never a numeric value, you can
declare it to be of type String:
Private S As String
You can then assign strings to this variable and manipulate it using string functions:
S = "Database"
S = Left(S, 4)
String * size
For example, to declare a string that is always 50 characters long, use code like this:
If you assign a string of fewer than 50 characters, EmpName is padded with enough trailing
spaces to total 50 characters. If you assign a string that is too long for the fixed-length string,
Visual Basic simply truncates the characters.
Because fixed-length strings are padded with trailing spaces, you may find the Trim and
RTrim functions, which remove the spaces, useful when working with them.
Fixed-length strings in standard modules can be declared as Public or Private. In forms and
class modules, fixed-length strings must be declared Private.
You can assign a string to a numeric variable if the string represents a numeric value. It's also
possible to assign a numeric value to a string variable. For example, place a command button,
text box, and list box on a form. Enter the following code in the command button's Click
event. Run the application, and click the command button.
strY = "100.23"
intX = strY ' Passes the string to a numeric
' variable.
List1.AddItem Cos(strY) ' Adds cosine of number in
' the string to the listbox.
strY = Cos(strY) ' Passes cosine to the
' string variable.
Text1.Text = strY ' String variable prints in
' the text box.
End Sub
Visual Basic will automatically coerce the variables to the appropriate data type. You should
use caution when exchanging strings and numbers; passing a non-numeric value in the string
will cause a run-time error to occur.
If you have a variable that will contain simple true/false, yes/no, or on/off information, you
can declare it to be of type Boolean. The default value of Boolean is False. In the following
example, blnRunning is a Boolean variable which stores a simple yes/no setting.
Date and time values can be contained both in the specific Date data type and in Variant
variables. The same general characteristics apply to dates in both types.
When other numeric data types are converted to Date, values to the left of the decimal
represent date information, while values to the right of the decimal represent time. Midnight
is 0, and midday is 0.5. Negative whole numbers represent dates before December 30, 1899.
Object variables are stored as 32-bit (4-byte) addresses that refer to objects within an
application or within some other application. A variable declared as Object is one that can
subsequently be assigned (using the Set statement) to refer to any actual object recognized by
the application.
When declaring object variables, try to use specific classes (such as TextBox instead of
Control or, in the preceding case, Database instead of Object) rather than the generic Object.
Visual Basic can resolve references to the properties and methods of objects with specific
types before you run an application. This allows the application to perform faster at run time.
Specific classes are listed in the Object Browser.
When working with other applications' objects, instead of using a Variant or the generic
Object, declare objects as they are listed in the Classes list in the Object Browser. This
ensures that Visual Basic recognizes the specific type of object you're referencing, allowing
the reference to be resolved at run time.
A Variant variable is capable of storing all system-defined types of data. You don't have to
convert between these types of data if you assign them to a Variant variable; Visual Basic
automatically performs any necessary conversion. For example:
OR
OtherValue = “2500”
While you can perform operations on Variant variables without much concern for the kind of
data they contain, there are some traps you must avoid.
If you are concatenating strings, use the & operator instead of the + operator.
In addition to being able to act like the other standard data types, Variants can also contain
three special values: Empty, Null, and Error.
The following table shows the supported data types, including storage sizes and ranges.
Note : Arrays of any data type require 20 bytes of memory plus 4 bytes for each array
dimension plus the number of bytes occupied by the data itself. The memory occupied by the
data can be calculated by multiplying the number of data elements by the size of each
element. For example, the data in a single-dimension array consisting of 4 Integer data
elements of 2 bytes each occupies 8 bytes. The 8 bytes required for the data plus the 24 bytes
of overhead brings the total memory requirement for the array to 32 bytes.
A Variant containing an array requires 12 bytes more than the array alone.
In addition to being able to act like the other standard data types, Variants can also contain
three special values: Empty, Null, and Error.
Sometimes you need to know if a value has ever been assigned to a created variable. A
Variant variable has the Empty value before it is assigned a value. The Empty value is a
special value different from 0, a zero-length string (""), or the Null value. You can test for the
Empty value with the IsEmpty function:
If IsEmpty(Z) Then Z = 0
When a Variant contains the Empty value, you can use it in expressions; it is treated as either
0 or a zero-length string, depending on the expression.
The Empty value disappears as soon as any value (including 0, a zero-length string, or Null)
is assigned to a Variant variable. You can set a Variant variable back to Empty by assigning
the keyword Empty to the Variant.
Dim Value
Private Sub Command1_Click()
If IsEmpty(Value) Then „Return True If Executed Before
MsgBox IsEmpty(Value) „Command2_Click()
Else
MsgBox IsEmpty(False)
End If
End Sub
Private Sub Command2_Click()
Value = 25
If IsEmpty(Value) Then „Return False Whenever Executed
MsgBox IsEmpty(Value)
Else
MsgBox IsEmpty(False)
End If
End Sub
Private Sub Command3_Click()
Value = Empty
MsgBox IsEmpty(Value) „Return True Whenver Executed
End Sub
The Variant data type can contain another special value: Null. Null is commonly used in
database applications to indicate unknown or missing data. Because of the way it is used in
databases, Null has some unique characteristics:
Expressions involving Null always result in Null. Thus, Null is said to "propagate"
through expressions; if any part of the expression evaluates to Null, the entire
expression evaluates to Null.
Passing Null, a Variant containing Null, or an expression that evaluates to Null as an
argument to most functions causes the function to return Null.
Null values propagate through intrinsic functions that return Variant data types.
Z = Null
You can use the IsNull function to test if a Variant variable contains Null:
If you assign Null to a variable of any type other than Variant, a trappable error occurs.
Assigning Null to a Variant variable doesn't cause an error, and Null will propagate through
expressions involving Variant variables (though Null does not propagate through certain
functions). You can return Null from any Function procedure with a Variant return value.
Variables are not set to Null unless you explicitly assign Null to them, so if you don't use
Null in your application, you don't have to write code that tests for and handles it.
In a Variant, Error is a special value used to indicate that an error condition has occurred in a
procedure. However, unlike for other kinds of errors, normal application-level error handling
does not occur. This allows you, or the application itself, to take some alternative based on
the error value. Error values are created by converting real numbers to error values using the
CVErr function.
The Nothing keyword is used to disassociate an object variable from an actual object. Use the
Set statement to assign Nothing to an object variable. For example:
Several object variables can refer to the same actual object. When Nothing is assigned to an
object variable, that variable no longer refers to an actual object. When several object
variables refer to the same object, memory and system resources associated with the object to
which the variables refer are released only after all of them have been set to Nothing, either
explicitly using Set, or implicitly after the last object variable set to Nothing goes out of
scope.
Dim X As CommandButton
Private Sub Command1_Click()
If (X Is Nothing) Then „Will be True
MsgBox "X object variable yet has not been initialized."
End If
End Sub
Private Sub Command2_Click()
Set X = Command1 „Will be False
If (X Is Nothing) Then
MsgBox "X object variable yet has not been initialized."
Else
MsgBox "X has been initialized."
End If
End Sub
Private Sub Command3_Click()
Set X = Nothing „assignment of Nothing
If (X Is Nothing) Then „Will be true
MsgBox "X object variable yet has not been initialized."
Else
MsgBox "X has been initialized with."
End If
End Sub
Visual Basic provides several conversion functions you can use to convert values into a
specific data type. To convert a value to Currency, for example, you use the CCur function:
Note :
Values passed to a conversion function must be valid for the destination data type or an error
occurs. For example, if you attempt to convert a Long to an Integer, the Long must be within
the valid range for the Integer data type.
You can combine variables of several different types to create user-defined types (known as
structs in the C programming language). User-defined types are useful when you want to
create a single variable that records several related pieces of information.
You create a user-defined type with the Type statement, which must be placed in the
Declarations section of a module. User-defined types can be declared as Private or Public
with the appropriate keyword. For example:
-or-
For example, you could create a user-defined type that records information about a computer
system:
You can declare local, private module-level, or public module-level variables of the same
user-defined type:
The following table illustrates where, and with what scope, you can declare user-defined
types and their variables.
Note:
If declared using the Dim keyword, user-defined types in Standard or Class modules will
default to Public. If you intend a user-defined type to be private, make sure you declare it
using the Private keyword.
Assigning and retrieving values from the elements of this variable is similar to setting and
getting properties:
MySystem.CPU = "486"
If MySystem.PurchaseDate > #1/1/92# Then
You can also assign one variable to another if they are both of the same user-defined type.
This assigns all the elements of one variable to the same elements in the other variable.
YourSystem = MySystem
Type SystemInfo
CPU As Variant
Memory As Long
DiskDrives(25) As String ' Fixed-size array.
VideoColors As Integer
Cost As Currency
PurchaseDate As Variant
End Type
Type SystemInfo
CPU As Variant
Memory As Long
DiskDrives() As String ' Dynamic array.
VideoColors As Integer
Cost As Currency
PurchaseDate As Variant
End Type
You can access the values in an array within a user-defined type in the same way that you
access the property of an object.
Follow the same rules to access the components of this data structure.
AllSystems(5).CPU = "386SX"
AllSystems(5).DiskDrives(2) = "100M SCSI"
Note If you want to pass a user-defined type in a form module, the procedure must be
private.
You can return user-defined types from functions, and you can pass a user-defined type
variable to a procedure as one of the arguments. User-defined types are always passed by
reference, so the procedure can modify the argument and return it to the calling procedure, as
illustrated in the previous example.
Note Because user-defined types are always passed by reference, all of the data contained in
the user-defined type will be passed to and returned from the procedure. For user-defined
types that contain large arrays, this could result in poor performance, especially in
client/server applications where a procedure may be running on a remote machine. In such a
situation, it is better to extract and pass only the necessary data from the user-defined type.
Tip Because the Variant data type can store many different types of data, a Variant array
can be used in many situations where you might expect to use a user-defined type. A Variant
array is actually more flexible than a user-defined type, because you can change the type of
data you store in each element at any time, and you can make the array dynamic so that you
can change its size as necessary. However, a Variant array always uses more memory than an
equivalent user-defined type.
Nesting data structures can get as complex as you like. In fact, user-defined types can contain
other user-defined types, as shown in the following example. To make your code more
readable and easier to debug, try to keep all the code that defines user-defined data types in
one module.
Type DriveInfo
Type As String
Size As Long
End Type
Type SystemInfo
CPU As Variant
Memory As Long
DiskDrives(26) As DriveInfo
Cost As Currency
PurchaseDate As Variant
End Type
Arrays
If you have programmed in other languages, you're probably familiar with the concept of
arrays. Arrays allow you to refer to a series of variables by the same name and to use a
number (an index) to tell them apart. This helps you create smaller and simpler code in many
situations, because you can set up loops that deal efficiently with any number of cases by
using the index number. Arrays have both upper and lower bounds, and the elements of the
array are contiguous within those bounds. Because Visual Basic allocates space for each
index number, avoid declaring an array larger than necessary.
Note: The arrays discussed in this section are arrays of variables, declared in code. They are
different from the control arrays you specify by setting the Index property of controls at
design time. Arrays of variables are always contiguous; unlike control arrays, you cannot
load and unload elements from the middle of the array.
All the elements in an array have the same data type. Of course, when the data type is
Variant, the individual elements may contain different kinds of data (objects, strings,
numbers, and so on). You can declare an array of any of the fundamental data types,
including user-defined types.
In Visual Basic there are two types of arrays: a fixed-size array which always remains the
same size, and a dynamic array whose size can change at run-time.
There are three ways to declare a fixed-size array, depending on the scope you want the array
to have:
To create a public array, use the Public statement in the Declarations section of a
module to declare the array.
To create a module-level array, use the Private statement in the Declarations section
of a module to declare the array.
To create a local array, use the Private statement in a procedure to declare the array.
When declaring an array, follow the array name by the upper bound in parentheses. The
upper bound cannot exceed the range of a Long data type (-2,147,483,648 to 2,147,483,647).
For example, these array declarations can appear in the Declarations section of a module:
The first declaration creates an array with 15 elements, with index numbers running from 0 to
14. The second creates an array with 21 elements, with index numbers running from 0 to 20.
The default lower bound is 0.
To specify a lower bound, provide it explicitly (as a Long data type) using the To keyword:
In the preceding declarations, the index numbers of Counters range from 1 to 15, and the
index numbers of Sums range from 100 to 120.
Multidimensional Arrays
Sometimes you need to keep track of related information in an array. For example, to keep
track of each pixel on your computer screen, you need to refer to its X and Y coordinates.
This can be done using a multidimensional array to store the values.
With Visual Basic, you can declare arrays of multiple dimensions. For example, the
following statement declares a two-dimensional 10-by-10 array within a procedure:
You can extend this to more than two dimensions. For example:
This declaration creates an array that has three dimensions with sizes 4 by 10 by 15. The total
number of elements is the product of these three dimensions, or 600.
Note When you start adding dimensions to an array, the total storage needed by the array
increases dramatically, so use multidimensional arrays with care. Be especially careful with
Variant arrays, because they are larger than other data types.
You can efficiently process a multidimensional array by using nested For loops. For
example, these statements initialize every element in MatrixA to a value based on its location
in the array:
For I = 1 To 10
For J = 1 To 10
MatrixA(I, J) = I * 10 + J
Next J
Next I
Dynamic Arrays
Sometimes you may not know exactly how large to make an array. You may want to have the
capability of changing the size of the array at run time.
A dynamic array can be resized at any time. Dynamic arrays are among the most flexible and
convenient features in Visual Basic, and they help you to manage memory efficiently. For
example, you can use a large array for a short time and then free up memory to the system
when you're no longer using the array.
The alternative is to declare an array with the largest possible size and then ignore array
elements you don't need. However, this approach, if overused, might cause the operating
environment to run low on memory.
Dim DynArray()
ReDim DynArray(X + 1)
The ReDim statement can appear only in a procedure. Unlike the Dim and Static statements,
ReDim is an executable statement — it makes the application carry out an action at run time.
The ReDim statement supports the same syntax used for fixed arrays. Each ReDim can
change the number of elements, as well as the lower and upper bounds, for each dimension.
However, the number of dimensions in the array cannot change.
For example, the dynamic array Matrix1 is created by first declaring it at the module level:
Sub CalcValuesNow ()
.
.
.
ReDim Matrix1(19, 29)
End Sub
The ReDim statement shown here allocates a matrix of 20 by 30 integers (at a total size of
600 elements). Alternatively, the bounds of a dynamic array can be set using variables:
ReDim Matrix1(X, Y)
Note You can assign strings to resizable arrays of bytes. An array of bytes can also be
assigned to a variable-length string. Be aware that the number of bytes in a string varies
among platforms. On Unicode platforms the same string contains twice as many bytes as it
does on a non-Unicode platform.
Each time you execute the ReDim statement, all the values currently stored in the array are
lost. Visual Basic resets the values to the Empty value (for Variant arrays), to zero (for
numeric arrays), to a zero-length string (for string arrays), or to Nothing (for arrays of
objects).
This is useful when you want to prepare the array for new data, or when you want to shrink
the size of the array to take up minimal memory. Sometimes you may want to change the size
of the array without losing the data in the array. You can do this by using ReDim with the
Preserve keyword. For example, you can enlarge an array by one element without losing the
values of the existing elements using the UBound function to refer to the upper bound:
Only the upper bound of the last dimension in a multidimensional array can be changed when
you use the Preserve keyword; if you change any of the other dimensions, or the lower bound
of the last dimension, a run-time error occurs. Thus, you can use code like this:
Control structures allow you to control the flow of your program's execution. If left
unchecked by control-flow statements, a program's logic will flow through statements from
left to right, and top to bottom. While some very simple programs can be written with only
this unidirectional flow, and while some flow can be controlled by using operators to regulate
precedence of operations, most of the power and utility of any programming language comes
from its ability to change statement order with structures and loops.
Topics:
Decision Structures
An introduction to decision structures used for branching.
Loop Structures
An introduction to loop structures used to repeat processes.
Decision Structures:
Visual Basic procedures can test conditions and then, depending on the results of that test,
perform different operations. The decision structures that Visual Basic supports include:
If...Then
If...Then...Else
Select Case
1. If...Then
Use an If...Then structure to execute one or more statements conditionally. You can use
either a single-line syntax or a multiple-line block syntax:
OR
If condition Then
Statement Block
End If
The condition is usually a comparison, but it can be any expression that evaluates to a
numeric value. Visual Basic interprets this value as True or False; a zero numeric value is
False, and any nonzero numeric value is considered True. If condition is True, Visual Basic
executes all the statements following the Then keyword. You can use either single-line or
multiple-line syntax to execute just one statement conditionally (these two examples are
equivalent):
OR
Notice that the single-line form of If...Then does not use an End If statement. If you want to
execute more than one line of code when condition is True, you must use the multiple-line
block If...Then...End If syntax.
2. If...Then...Else
Use an If...Then...Else block to define several blocks of statements, one of which will
execute:
If condition1 Then
[statementblock-1]
[statementblock-2]] ...
[Else
[statementblock-n]]
End If
Visual Basic first tests condition1. If it's False, Visual Basic proceeds to test condition2, and
so on, until it finds a True condition. When it finds a True condition, Visual Basic executes
the corresponding statement block and then executes the code following the End If. As an
option, you can include an Else statement block, which Visual Basic executes if none of the
conditions are True.
If...Then…ElseIf is really just a special case of If...Then...Else. Notice that you can have any
number of ElseIf clauses, or none at all. You can include an Else clause regardless of whether
you have ElseIf clauses.
For example, your application could perform different actions depending on which control in
a menu control array was clicked:
Notice that you can always add more ElseIf parts to your If...Then structure. However, this
syntax can get tedious to write when each ElseIf compares the same expression to a different
value. For this situation, you can use a Select Case decision structure.
3. Select Case:
Visual Basic provides the Select Case structure as an alternative to If...Then...Else for
selectively executing one block of statements from among multiple blocks of statements. A
Select Case statement provides capability similar to the If...Then...Else statement, but it
makes code more readable when there are several choices.
A Select Case structure works with a single test expression that is evaluated once, at the top
of the structure. Visual Basic then compares the result of this expression with the values for
each Case in the structure. If there is a match, it executes the block of statements associated
with that Case:
Each expressionlist is a list of one or more values. If there is more than one value in a single
list, the values are separated by commas. Each statementblock contains zero or more
statements. If more than one Case matches the test expression, only the statement block
associated with the first matching Case will execute. Visual Basic executes statements in the
Case Else clause (which is optional) if none of the values in the expression lists matches the
test expression.
For example, suppose you added another command to the Edit menu in the If...Then...Else
example. You could add another ElseIf clause, or you could write the function with Select
Case:
Notice that the Select Case structure evaluates an expression once at the top of the structure.
In contrast, the If...Then...Else structure can evaluate a different expression for each ElseIf
statement. You can replace an If...Then...Else structure with a Select Case structure only if
the If statement and each ElseIf statement evaluates the same expression.
Loop Structures:
Loop structures allow you to execute one or more lines of code repetitively. The loop
structures that Visual Basic supports include:
Do...Loop
For...Next
For Each...Next
1. Do...Loop
Use a Do loop to execute a block of statements an indefinite number of times. There are
several variations of the Do...Loop statement, but each evaluates a numeric condition to
determine whether to continue execution. As with If...Then, the condition must be a value or
expression that evaluates to False (zero) or to True (nonzero).
In the following Do...Loop, the statements execute as long as the condition is True:
Do While condition
statements 1
Loop
When Visual Basic executes this Do loop, it first tests condition. If condition is False (zero),
it skips past all the statements. If it's True (nonzero), Visual Basic executes the statements
and then goes back to the Do While statement and tests the condition again.
Consequently, the loop can execute any number of times, as long as condition is nonzero or
True. The statements never execute if condition is initially False. For example, this procedure
counts the occurrences of a target string within another string by looping as long as the target
string is found:
If the target string doesn't occur in the other string, then InStr returns 0, and the loop doesn't
execute.
Another variation of the Do...Loop statement executes the statements first and then tests
condition after each execution. This variation guarantees at least one execution of statements:
Do
Statements 2
Loop While condition
Two other variations are analogous to the previous two, except that they loop as long as
condition is False rather than True.
Do Until condition
Statements 3
Loop
-----------------------------------------------------------------------------------
Do
Statements
4
Loop Until condition
2. For...Next
Do loops work well when you don't know how many times you need to execute the
statements in the loop. When you know you must execute the statements a specific number of
times, however, a For…Next loop is a better choice. Unlike a Do loop, a For loop uses a
variable called a counter that increases or decreases in value during each repetition of the
loop. The syntax is:
statements
Next [counter]
The arguments counter, start, end, and increment are all numeric.
Note The increment argument can be either positive or negative. If increment is positive,
start must be less than or equal to end or the statements in the loop will not execute. If
increment is negative, start must be greater than or equal to end for the body of the loop to
execute. If Step isn't set, then increment defaults to 1.
2. Tests to see if counter is greater than end. If so, Visual Basic exits the loop.
(If increment is negative, Visual Basic tests to see if counter is less than end.)
This code prints the names of all the available Screen fonts:
3. For Each...Next
A For Each...Next loop is similar to a For...Next loop, but it repeats a group of statements for
each element in a collection of objects or in an array instead of repeating the statements a
specified number of times. This is especially helpful if you don't know how many elements
are in a collection.
statements
Next element
For example, the following Sub procedure opens Biblio.mdb and adds the name of each table
to a list box.
Sub ListTableDefs()
Dim objDb As Database
Dim MyTableDef as TableDef
Set objDb = OpenDatabase("c:\vb\biblio.mdb", _
True, False)
For Each MyTableDef In objDb.TableDefs()
List1.AddItem MyTableDef.Name
Next MyTableDef
End Sub
For collections, element can only be a Variant variable, a generic Object variable, or
an object listed in the Object Browser.
You cannot use For Each...Next with an array of user-defined types because a Variant
cannot contain a user-defined type.
You can place control structures inside other control structures (such as an If...Then block
within a For...Next loop). A control structure placed inside another control structure is said to
be nested.
Control structures in Visual Basic can be nested to as many levels as you want. It's common
practice to make nested decision structures and loop structures more readable by indenting
the body of the decision structure or loop.
For example, this procedure prints all the font names that are common to both the Printer and
Screen:
Notice that the first Next closes the inner For loop and the last For closes the outer For loop.
Likewise, in nested If statements, the End If statements automatically apply to the nearest
prior If statement. Nested Do...Loop structures work in a similar fashion, with the innermost
Loop statement matching the innermost Do statement.
The Exit statement allows you to exit directly from a For loop, Do loop, Sub procedure, or
Function procedure. The syntax for the Exit statement is simple: Exit For can appear as
many times as needed inside a For loop, and Exit Do can appear as many times as needed
inside a Do loop:
The Exit Do statement works with all versions of the Do loop syntax.
Exit For and Exit Do are useful because sometimes it's appropriate to quit a loop
immediately, without performing any further iterations or statements within the loop. For
example, in the previous example that printed the fonts common to both the Screen and
Printer, the code continues to compare Printer fonts against a given Screen font even when a
match has already been found with an earlier Printer font. A more efficient version of the
function would exit the loop as soon as a match is found:
When you use an Exit statement to break out of a loop, the value of the counter variable
differs, depending on how you leave the loop:
When you complete a loop, the counter variable contains the value of the upper bound
plus the step.
When you exit a loop prematurely, the counter variable retains its value subject to the
usual rules on scope.
When you iterate off the end of a collection, the counter variable contains Nothing if
it's an Object data type, and contains Empty if it's a Variant data type.
You can also exit a procedure from within a control structure. The syntax of Exit Sub and
Exit Function is similar to that of Exit For and Exit Do in the previous section, "Exiting a
Control Structure." Exit Sub can appear as many times as needed, anywhere within the body
of a Sub procedure. Exit Function can appear as many times as needed, anywhere within
the body of a Function procedure.
Exit Sub and Exit Function are useful when the procedure has done everything it needs to
do and can return immediately. For example, if you want to change the previous example so
it prints only the first common Printer and Screen font it finds, you would use Exit Sub:
You can simplify programming tasks by breaking programs into smaller logical components.
These components — called procedures — can then become building blocks that let you
enhance and extend Visual Basic.
Procedures are useful for condensing repeated or shared tasks, such as frequently used
calculations, text and control manipulation, and database operations.
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.
Topics:
1. Sub Procedures
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.
Each time the 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.
In Visual Basic, it's useful to distinguish between two types of Sub procedures, general
procedures and event procedures.
General Procedures
A general procedure tells the application how to perform a specific task. Once a general
procedure is defined, it must be specifically invoked by the application. By contrast, an event
procedure remains idle until called upon to respond to events caused by the user or triggered
by the system.
Why create general procedures? One reason 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. This
eliminates the need to duplicate code and also makes the application easier to maintain.
Following Figure illustrates the use of a general procedure. Code in the Click events calls the
ButtonManager Sub procedure, which runs its own code, and then returns control to the Click
event procedure.
Event Procedures
When an object in Visual Basic recognizes that an event has occurred, it automatically
invokes the event procedure using the name corresponding to the event. Because the name
establishes an association between the object and the code, event procedures are said to be
attached to forms and controls.
An event procedure for a control combines the control's actual name (specified in the
Name property), an underscore (_), and the event name. For instance, if you want a
command button named cmdPlay to invoke an event procedure when it is clicked, use
the procedure cmdPlay_Click.
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 Visual Basic, 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.
It's also a good idea to set the Name property of your controls before you start writing event
procedures for them. If you change the name of a control after attaching a procedure to it,
you must also change the name of the procedure to match the new name of the control.
Otherwise, Visual Basic won't be able to match the control to the procedure. When a
procedure name does not match a control name, it becomes a general procedure.
2. Function Procedures:
Visual Basic includes built-in, or intrinsic functions, like Sqr, Cos or Chr. In addition, you
can use the Function statement to write your own Function procedures.
Like a Sub procedure, a Function procedure is a separate procedure that can take arguments,
perform a series of statements, and change the value of its arguments. Unlike a Sub
procedure, a Function procedure can return a value to the calling procedure.
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.
You return a value by assigning it to the procedurename itself. When the Function
procedure returns a value, this value can then become part of a larger expression.
For example:
You call a Function procedure the same way you call any of the built-in functions in Visual
Basic:
Label1.Caption = SqrRadius(X1,X2,Y1,Y2)
Or
RSquare = SqrRadius(X1,X2,Y1,Y2)
Calling Procedures:
The techniques for calling procedures vary, depending on the type of procedure, where it's
located, and how it's used in your application. The following sections describe how to call
Sub and Function procedures.
A Sub procedure differs from a Function procedure in that a Sub procedure cannot be called
by using its name within an expression. A call to a Sub is a stand-alone statement. Also, a
Sub does not return a value in its name as does a function. However, like a Function, a Sub
can modify the values of any variables passed to it.
Note:
When you use the Call syntax, arguments must be enclosed in parentheses. If you omit the
Call keyword, you must also omit the parentheses around the arguments.
Usually, you call a function procedure you've written yourself the same way you call an
intrinsic Visual Basic function like Abs; that is, by using its name in an expression:
Print 10 * ToDec() 1
X = ToDec()
2
It's also possible to call a function just like you would call a Sub procedure. The following
statements both call the same function:
Call Year(Now) 1
Year Now 2
When you call a function this way, Visual Basic throws away or ignore the return value.
Public procedures in other modules can be called from anywhere in the project. You might
need to specify the module that contains the procedure you're calling. The techniques for
doing this vary, depending on whether the procedure is located in a form, class, or standard
module.
1. Procedures in Forms
All calls from outside the form module must point to the form module containing the
procedure. If a procedure named SomeSub is in a form module called Form1, then you can
call the procedure in Form1 by using this statement:
Call Form1.SomeSub(arguments)
Like calling a procedure in a form, calling a procedure in a class module requires that the call
to the procedure be qualified with a variable that points to an instance of the class. For
example, DemoClass is an instance of a class named Class1:
DemoClass.SomeSub
However, unlike a form, the class name cannot be used as the qualifier when referencing an
instance of the class. The instance of the class must be first be declared as an object variable
(in this case, DemoClass) and referenced by the variable name.
If a procedure name is unique, you don't need to include the module name in the call. A call
from inside or outside the module will refer to that unique procedure. A procedure is unique
if it appears only in one place.
If two or more modules contain a procedure with the same name, you may need to qualify it
with the module name. A call to a common procedure from the same module runs the
procedure in that module. For example, with a procedure named CommonName in Module1
and Module2, a call to CommonName from Module2 will run the CommonName procedure
in Module2, not the CommonName procedure in Module1.
A call to a common procedure name from another module must specify the intended module.
For example, if you want to call the CommonName procedure in Module2 from Module1,
use:
Module2.CommonName(arguments)
Collection is a way of grouping a set of related items. Collections are used in Visual Basic to
keep track of many things, such as the loaded forms in your program (the Forms collection),
or all the controls on a form (the Controls collection).
Visual Basic provides the generic Collection class to give you the ability to define your own
collections. You can create as many Collection objects — that is, instances of the Collection
class — as you need.
For example, collections are a good way to keep track of multiple forms in Multiple
Document Interface (MDI) Applications in which the user can open any number of document
windows.
The advantage of a collection over an array is that the collection lets you access its items via
a key.
If a city name is the key in the Temperatures () array, you can recall the temperature in Delhi
only by providing the index value of the element, but what if you don’t know about the
element’s index? Simply you can’t access in case of an array, but if this is the case of a
collection, you don’t have to remember the index value because you can also access item or
element by its key. For Temperatures () collection you can access temperature of Delhi by
providing the key as below:
The Item argument is a method of the collection object that returns a collection item based on
its key or index. Or if you know the index of Delhi’s entry in the collection you can use a
statement like:
Of Course, if you are going to access a collection’s item with its index, there is no advantage
to using collections over arrays.
Declaring a Collection:
The keyword New tells Visual Basic to create a new collection and name it by specified
name.
Example:
Each Collection object comes with properties and methods you can use to insert, delete, and
retrieve the items in the collection.
Add method:
The Add method adds new items to the collection and it has the following syntax;
Or in Simplest Form-
To add a new element to a collection, assign its value to the item argument and its key to the
key argument.
To place the new item in a specific location in the collection, specify one of the arguments
before or after (but not both).To insert the new item before a specific element whose key (or
index) you will specify, use the before argument. To place the new item after an item,
specify this item’s key or index with the after argument.
Example:
Contains extra comma which denotes the lack of the before argument. The Add method
supports named arguments, so the previous statement could also be written as:
Collections are not stored, nor do they have a method to automatically sort their items. To
maintain an ordered collection of objects, use the before and after arguments. In most
practical situations, however, you won’t care about sorting a collection’s items. You sort
arrays to simplify access to their elements. You don’t have to do anything special to access
the elements of collections.
Remove Method:
The Remove method removes an item from a collection. The index argument can be either
the position of the item you want to delete or the item’s key.
CollectionName.Remove (index/Key)
Example:
Temperatures.Remove ("Banglore")
Item Method:
The Item method returns the value of an item in the collection. The syntax is:
HottestCity = Temperatures.Item(“Tamilnadu”)
The Item method is the default method for a collection object, so you can omit it when you
access an item in a collection. The previous example could also be written as:
HottestCity = Temperatures(“Tamilnadu”)
Note:
Collections maintain their indices automatically as elements are added and deleted. The
index of a given element, therefore, changes during the course of a program and you
shouldn’t save an item’s index value and expect to use it to retrieve the same element later in
your program. Use keys for this purpose.
Counting a Collection:
The Count property returns the number of items in the collection. To find out how many
cities have been entered so far in the Temperatures collection, use the following statement:
Temperatures.Count
You can also use the Count property to scan all the elements of the collection, with a
For……Next loop such as the following.
Keywords:
Keywords are the reserve special words that have predefined meaning to the language
processor. Visual Basic provides following 42 keywords.
Operators:
Operators are the special symbols that performs the specified operations on their operands.
Visual Basic provides following Operators.