Welcome to Visual Basic 6 (VB6) Beginners Guide


Visual Basic is one of the most popular programming languages.This site is dedicated to helping you learn and advance in Visual Basic 6.Assuming you all are Visual Basic 6 (VB6) Beginners Guide, each and every lesson in this tutorial is explained step by step with examples and source code. If you have suggestions that would make the tutorials more interesting, please do not hesitate to pass them along.

Making & Running an Executable File


You can make an executable file (.exe) from Visual Basic using the following procedure.

To make an executable file in Visual Basic

Ø From the File menu, choose Make projectname .exe where projectname is the application name for the project.

Ø Type a file name, or browse through the directories and select an existing file name to overwrite an existing executable with a newer version.

Ø 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, as shown in Figure 10.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.

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

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

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

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.



Using Other Applications' Objects


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 add objects to the toolbox, see "Adding Controls to a Project" earlier in this chapter.

To make another application's objects available in your code, but not as controls, set a reference to that application's object library.

To add a reference to another application's object library

Ø From the Project menu, choose References.

Ø The References dialog box is displayed, as shown in Figure 10.3.

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

Ø Choose OK to add the selected references to your project.

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.



Using a Resource File

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.


To add a file to a project

Ø From the Project menu, select Add File.

Ø The Add File dialog box is displayed.

Ø Select an existing resource file (.res) and choose Open.

A single project can have only one resource file; if you add a second file with a .res extension, an error occurs.

Adding Controls to a Project


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. The basic set of standard controls that always appear in the toolbox is described in "Forms, Controls, and Menus."

Adding ActiveX Controls to a Project

You can add ActiveX controls and insertable objects to your project by adding them to the toolbox.

To add a control to a project's toolbox

Ø From the Project menu, choose Components.

Ø The Components dialog box is displayed, as shown in Figure 10.2. The items listed in this dialog box include all registered ActiveX controls, insertable objects, and ActiveX designers.

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

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

Removing Controls from a Project

To remove a control from a project

Ø From the Project menu, choose Components.

Ø The Components dialog box is displayed.

Ø Clear the check box next to each control you want to remove.

Ø The control icons will be removed from the toolbox.

The Project Explorer

As you create, add, or remove editable files from a project, Visual Basic reflects your changes in the Project Explorer window, which contains a current list of the files in the project. The Project Explorer window in Figure 10.1 shows some of the types of files you can include in a Visual Basic project.

The Project File

Each time you save a project, Visual Basic updates the project file (.vbp). A project file contains the same list of files that appears in the Project Explorer window, as well as references to the ActiveX controls and insertable objects that are used in the project.

You can open an existing project file by double-clicking its icon, by choosing the Open Project command from the File menu, or by dragging the file and dropping it on the Project Explorer window.

Structure of Visual basic 6.0 Project

The following section describe the different types of files and objects that you can include in a project.

Ø Form Modules

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

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

Standard modules (.bas file name extension) can contain public or module-level declarations of types, constants, variables, external procedures, and public procedures.

Ø Resource Files

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

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 and Property Page Modules

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.

Ø Components

In addition to files and modules, several other types of components can be added to the project.

Ÿ ActiveX Controls

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

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

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

Ÿ ActiveX Designers

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.

Ÿ Standard Controls

Standard controls are supplied by Visual Basic. Standard controls, such as the command button or frame control, are always included in the toolbox, unlike ActiveX controls and insertable objects, which can be removed from or added to the toolbox.

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.

To add an additional project to the current project group

Ø From the File menu, choose Add Project.The Add Project dialog box is displayed.

Ø Select an existing project or a new project type, and choose Open.

To remove a project from the current project group

Ø Select a project or a component of a project in the Project Explorer.

Ø From the File menu, choose Remove Project.

Working with Projects

As you develop an application, you work with a project to manage all the different files that make up the application. A project consists of:

Ø One project file that keeps track of all the components (.vbp).

Ø One file for each form (.frm).

Ø One binary data file for each form containing data for properties of controls on the form (.frx). These files are not editable and are automatically generated for any .frm file that contains binary properties, such as Picture or Icon.

Ø Optionally, one file for each class module (.cls).

Ø Optionally, one file for each standard module (.bas).

Ø Optionally, one or more files containing ActiveX controls (.ocx).

Ø Optionally, a single resource file (.res).

The project file is simply a list of all the files and objects associated with the project, as well as information on the environment options you set. This information is updated every time you save the project. All of the files and objects can be shared by other projects as well.

When you have completed all the files for a project, you can convert the project into an executable file (.exe): From the File menu, choose the Make project.exe command. With the Professional and Enterprise editions of Visual Basic, you can also create other types of executable files such as .ocx and .dll files. References in this chapter assume a standard .exe project.

Managing Projects

Project is a collection of all the Forms, Modules and Controls that make up the application. The Project Explorer window displays a list of all the Forms, Modules, and Custom controls in an application.

In this chapter you’ll discuss the structure of Visual Basic project. In Visual basic 6.0, you can load multiple projects; the procedure is explained in this chapter. You will also discuss how executables are created in Visual Basic

Project is a collection of all the Forms, Modules and Controls that make up the application. The objective of this chapter is to explain to the user the structure of Visual basic 6.0 project.

At the end of this chapter, the user will be able to :

Ø Create a Visual Basic project.

Ø How to open multiple projects simultaneously in Visual basic 6.0

Ø How to create executables in Visual Basic.

Methods

You have seen Functions and Procedures in Visual Basic; Visual Basic also includes Methods . Methods operate in the same manner as procedures and functions , but they are components of specific objects, just as properties and field names are. To call a method , the syntax is as followed :

Objectname.Method

Hence to call the print method you could write Debug.Print .

Visual Basic has no print procedure. Instead, all the objects to which you can write have a method named Print . If you want to print a string say "Visual Basic" to a Form named TryForm , you would write the following code :

TryForm.Print "Visual Basic"

The printer , in Visual Basic is represented by a special object named Printer, Hence if you want to write to the printer, you will have to type :

Printer.Print "Visual Basic"

Often Visual Basic allows you to omit the object name when using a method . If you do this, Visual Basic directs the method to the object it believes you intended - usually the current Form. To avoid ambiguity, you can always use the full Object.Method naming Convention. Methods can act like procedures and functions . They can simply perform a service as the Print method does , or they can return values.

Returning an Array from a Function

It’s possible for a function to return an array of values now from Visual Basic 6.0 version onwards. For example, you may want to return an array of bytes from a function without having to perform conversions to and from a string.

Here’s a simple example of a function that returns an array of bytes:

Private Sub Form_Load()

Dim b As Byte

Dim I As Integer

Dim ReturnArray() As Byte

i = Cbyte(54)

ReturnArray() = ArrayFunction(b)

For i = 0 To Ubound(ReturnArray)

Debug.Print ReturnArray(i)

Next

End Sub

Public Function ArrayFunction(b As Byte) As Byte()

Dim x(2) As Byte

x(0) = b

x(1) = b + CByte(200)

x(2) = b + b

ArrayFunction = x

End Function

After running the above example, ReturnArray() would be a three-element array containing the values assigned to the array in the ArrayFunction. Note that the array must be of the same data type as the function (in this case, Byte). Because this is a function call, the array can be passed without the parentheses.


Procedures in Standard Modules

If the 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. A procedure is common if it appears in more than one place, for instance, in two different modules.

A call to a common procedure from the same module runs the procedure in that module. For example, a call to CommonName from Module2 will run the CommonName procedure in Module2, not the CommonName procedure in Module1, as shown in the above figure.

A call to a common procedure name from another module must specify the intended module, as shown in figure. For example, if you want to call the CommonName procedure in Module2 from Module1, you must specify the intended module:

Module2.CommonName(arguments)

Procedures in Class Modules


Like calling a procedure in some instance of 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 Class1:

Dim DemoClass as New Class1

DemoClass.SomeSub

However, unlike a Form, the class name cannot be used as the qualifier when referencing an instance of the class.

Calling Procedures in Other Modules


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.

Ø 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)

To call the procedure in a different instance (or copy) of a Form, use the variable that points to the instance to qualify the procedure name. The following code calls the SomeSub procedure contained in DemoForm, which is an instance of Form1.

Dim DemoForm As New Form1

DemoForm.SomeSub(arguments) ' Where DemoForm is an instance of Form1.

Calling the 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.

Calling Sub 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.

There are two ways to call a Sub procedure:

' Both of these statements call a Sub named MyProc.

Call MyProc (FirstArgument, SecondArgument)

MyProc FirstArgument, SecondArgument

It should be noted that 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.

Function Procedures

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:

' All of the following statements would call a function named ToDec.

Print 10 * ToDec

X = ToDec

If ToDec = 10 Then Debug.Print "Out of Range"

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)

Year Now

When you call a function this way, Visual Basic throws away the return value.

Passing Parameters

Usually the code in a procedure needs some information about the state of the program to do its job. This information is passed to the procedure as arguments when the procedure is called.

Argument Data Types

The arguments for procedures you write have the Variant data type by default. However, you can declare other data types for arguments. For example, the following function accepts a string and an integer:

Function Reverse (S As String, ByVal n As Integer)

' Reverses the first n characters in S.

Dim Temp As String, i As Integer

If n > Len(S) Then n = Len(S)

For i = n To 1 Step -1

Temp = Temp & Mid(S, i, 1)

Next

Reverse = Temp & Right(S, Len(S) - n)

End Function

Passing Arguments By Value

Only a copy of a variable is passed when a variable is passed by value. If the procedure changes the value, the change affects only the copy and not the variable itself. You must use the ByVal keyword to indicate a variable is passed by value.

For example:

Sub PostAccounts(ByVal intAcctNum as Integer)

.

. ' Place statements here.

.

End Sub

Arguments By Reference

Passing arguments by reference gives the procedure access to the actual variable contents in its memory address location. As a result, the variable’s value can be permanently changed by the procedure to which it is passed. Passing by reference is the default in Visual Basic.

If you specify a data type for an argument passed by reference, you must pass a value of that type for the argument. You can work around this by passing an expression, rather than a data type, for an argument. Visual Basic evaluates an expression and passes it as the required type if it can. The simplest way to turn a variable into an expression is to enclose it in parentheses. Using the Reverse function from the example in “Argument Data Types,” the following code turns a variable into an expression by enclosing it in parentheses:

Debug. Print Reverse ((V), 4) ' Turns the variable into an expression.

Optional Arguments

You can specify that arguments to a procedure are optional by placing the Optional keyword in the argument list. If you specify an optional argument, all subsequent arguments in the argument list must also be optional and declared with the Optional keyword. The optional arguments must be of the Variant data type. The two pieces of sample code below assumes there is a Form with a Command button and List box.

For example, this code provides all optional arguments:

Dim strName As String

Dim varAddress As Variant

Sub ListText(Optional x As String, Optional y As Variant)

List1.AddItem x

List1.AddItem y

End Sub

Private Sub Command1_Click()

strName = "yourname"

varAddress = 12345 ' Both arguments are provided.

Call ListText(strName, varAddress)

End Sub

This code, however, does not provide all optional arguments:

Dim strName As String

Dim varAddress As Variant

Sub ListText(x As String, Optional y As Variant)

List1.AddItem x

If Not IsMissing(y) Then

List1.AddItem y

End If

End Sub

Private Sub Command1_Click()

strName = "yourname" ' Second argument is not provided.

Call ListText(strName)

End Sub

Using an Indefinite Number of Arguments

Generally, the number of arguments in the procedure call must be the same as in the procedure specification. Using the ParamArray keyword allows you to specify that a procedure will accept an arbitrary number of arguments. This allows you to write functions like Sum:

Dim x As Variant

Dim y As Integer

Dim intSum As Integer

Sub Sum(ParamArray intNums())

For Each x In intNums

y = y + x

Next x

intSum = y

End Sub

Private Sub Command1_Click()

Sum 1, 3, 5, 7, 8

List1.AddItem intSum

End Sub

Creating Simpler Statements with Named Arguments

For many built-in functions, statements, and methods, Visual Basic provides the option of using named arguments as a shortcut for typing many argument values. With named arguments, you can provide any or all of the arguments, in any order, by assigning a value to the named argument. You do this by typing a colon followed by an equal sign (:=) and placing that assignment in any sequence delimited by the list separator character. You must notice that the arguments in the following example are in the reverse order of the actual syntax:

Set CurDB = OpenDatabase(exclusive:= False, source:= "Fox 2.5", _ readonly:= False, dbname:="C:\FoxData")

You can use named arguments with the functions and procedures you create, too. Visual Basic automatically associates argument names with their corresponding procedures.

Function ListText(strName As String, Optional varAddress As Variant)

List1.AddItem varAddress

List1.AddItem strName

End Sub

Private Sub Command1_Click()

ListText varAddress:=12345, strName:="Your Name"

End Sub

This is especially useful if your procedures have several optional arguments that you do not always need to specify.

Objects as Parameters

You have seen how to pass numeric values,strings, arrays as parameters . Visual Basic also allows you to pass Controls and Forms as parameters .

The syntax of passing objects as parameters to the procedures is similar to passing numeric values and variables . In the procedure declaration you should simply use the keywords Control or Form in place of Integers,Strings, and so on. For example :

Sub Check ( Buttn As Control )

Buttn.FontItalic=True

End Sub

In the calling routine , you pass the object as a parameter by using the objects name. You could pass a button named Butnext to the above procedure in the following manner :

Check Butnext

In a similar manner, you can declare a parameter to be a Form. You can set and examine the Form properties . You can pass the Form by name , or You can use the built-in variable Me , Which stands for the currently active Form.