Determines the number of workdays within a date range in visual basic

I used implicit If Statements (IIF) because they take less lines of code, and this procedure is convoluted enough without making is bigger! In case you aren't familiar with them, they are a hold-over from VBA.
The first argument is the expression, the second is what to do if it's true, the third is what to do if it's false.
The first part determines the number of days between 2 dates. The second part determines the number of whole weeks because each whole week has a Saturday & a Sunday in it. The last part determines if the range spanned a weekend but not a whole week so it can subtract the
weekend out.

Private Sub FindWorkDays()
Dim A1 As Date
Dim A2 As Date
Dim iWorkDays As Integer

A1 = Text1.Text
A2 = Text2.Text

iWorkDays = A2 - A1 + 1 - Int((A2 - A1 + 1) / 7) * 2 - _
IIf(Int((A2 - A1 + 1) / 7) = (A2 - A1 + 1) / 7, 0, _
IIf(WeekDay(A2) < WeekDay(A1), 2, 0)) - _
IIf((WeekDay(A1) = 1 Or WeekDay(A2) = 7), 1, 0)

Label1.Caption = iWorkDays

End Sub

To Pause your application for a length of time without a timer control

First put this code either in a module as a private function on a form

Public Declare Sub Sleep Lib "kernel32.dll" (ByVal dwMilliseconds As Long)

Then when you want to pause something just do this
Sleep 1000 'Pause for 1 second

Crystal Report in Visual basic

Crystal Report is a Report Writer that comes with the professional edition of Visual
Basic. It is used to perform the following functions.

1. Design how the report looks
2. Add groupings that break every time the data in this group is changed.
3. Add subtotals based on these groupings, if desired.

The Report Writer is designed in two steps.

1.Design the report layout in the crystal reports design environment.
Write code in your Visual Basic application that runs the report designed in the
previous step.
2. To access the design environment - simply click the Add – Ins | Report Designer
menu option. This brings up two registration screen which contains information for
registering

Creating formulas in data reports in Visual basic

If you want to create a formula to calculate numeric values, compare one value to
another and select alternative actions based on the comparison, join multiple text
strings into a single string, make data calculations or comparisons, etc.:



1 Click the Insert Formula button on the button bar. The Insert Formula dialog box
appears.
2 Enter a name for your formula and click OK. The Formula Editor appears. Use the
Formula Editor to create, test and modify your formula.
3 Enter fields, operators, and functions into the Formula text box by double-clicking
them in their respective list boxes. You can get complete information on each
available Function and Operator via the Help button.

Note Each formula is a text string that can be typed directly in to the Formula text
box as well as selecting components from the list boxes.

4 When finished editing, click the Accept button. Crystal Reports checks the formula
syntax, and if correct, closes the Formula Editor.
5 Place the formula field where you want it to appear in your report.

Adding a graph, chart to crystal report in Visual basic

Crystal Reports enables you to include sophisticated, colorful charts and graphs in
your reports.
When you add a graph to your report, you are graphing summary and subtotal
information. Before you can add a graph, therefore, you must have at least one group
and one summary or subtotal in your report. For example, if you have a sales report
grouped by State and a subtotal of Last Year’s Sales for each State, you can quickly
create a graph that will display sales by state.
Adding and modifying your graphs is easy in Crystal Reports with the use of the
Graph/Chart Expert. Use the Expert every time you create or modify graphs. The
Expert walks you through the creation of your graphs step-by-step.



1 Click the Insert Chart button on the button bar to access the Graph/Chart Expert.

Types

Tab

When you begin creating your graphs, you will need to choose one of the many
graph types available. To select a graph type, click the button that corresponds to
the graph type you want.

Data

Tab

In the Data Tab, select what data you want to graph on, how often you want it to
print (dependent on where you want it displayed), and what you want to show in
the graph.
The graph on drop-down box displays all the summaries and subtotals on your
report. Simply select which one you want to base your graph on.

Text

Tab

The Text Tab allows you to enter labels for your graph by inserting titles,
footnotes, and axis titles when appropriate. Simply type the text into the
corresponding boxes. The program will only use the labels appropriate for the
graph type that you chose earlier. The others will be ignored.

Options

Tab

The Options Tab enables you to place a legend on your graph, a maximum or
minimum limit on the graph values, or a number of other options.




OLE Objects
Crystal Reports is an OLE container application. Thus it allows you to place OLE
objects in your report. To do this:
1 Choose the Object command from the Insert menu.
2 Insert an existing object by choosing the Create from file option and selecting the
desired object, or create a new object by choosing the Create New option then an
object type. The corresponding application will open where you can create the
object as desired.
3 If you want to edit the object, simply double-click it and the program in which it
was created (or a similar application that allows such editing) will open.
4 Modify the object as desired, save it and Crystal Reports automatically updates the
object in your report.


Variables Used by All Modules in Visual basic

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:
Public intTemp As Integer

Note You can't declare public variables within a procedure, only within the
Declarations section of a module.

Variables Used Within a Module in Visual basic

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:

Private intTemp As Integer

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.

Passing Arguments By Reference in VB

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. For example, to pass a variable declared as an integer to a
procedure expecting a string as an argument, you would do the following:


Sub CallingProcedure()
Dim intX As Integer
intX = 12 * 3
Foo(intX)
End Sub

Sub Foo(Bar As String)
MsgBox Bar 'The value of Bar is the string "36".
End Sub

Adding Methods to the Object in Vb

Add a new subroutine to the class module. This sub must be publicly available
and named deposit. Add code to the new method to increase the balance by a
given amount.
Add a new function to the class module. This function should be publicly
available and named withdraw. Add code to the new method to decrease the
balance by a given amount.

Methods of Interfacing with the jet Database Engine

Visual Basic provides two methods of interfacing with the Jet database engine: the Data control and data access objects. While the Data control gives you limited ability to access existing databases without programming, the DAO model is a complete programming interface that gives you total control of the database. These two methods are not mutually exclusive; in fact, there are many situations where you will want to use both of them together.
The DAO model is a collection of object classes that model the structure of a
relational database system. They provide properties and methods that allow you
to accomplish all of the operations necessary to manage such a system, including
facilities for creating databases, defining tables, fields and indexes, establishing
relations between tables, navigating and querying the database, and so on.
The Jet database engine translates these operations on data access objects
into physical operations on the database files themselves, handling all the
mechanics of interfacing with the different supported databases.
Database programming in Visual Basic consists of creating data access
objects, such as Database, TableDef, Field, and Index objects, that correspond to
the various parts of the physical database you want to access. You use the
properties and methods of these objects to perform operations on the database.
You can display the results of these operations and accept input from the user on
Visual Basic forms, using both bound and unbound controls.
This approach simplifies the code you need to write and insulates you from
the underlying structure and mechanics of retrieving and updating data. It gives
you great flexibility, because you can use the same objects, properties, and
methods to work with a wide variety of supported database formats. Also, if you
change from one database format to another (for example, porting a local
Microsoft Access database to a SQL Server database on a network), you'll need
to make few changes in your code to accommodate the change. You can even
create applications that join tables from two or more different databases in a
single query or report.

Data Manipulation (DML) in Visual basic

DML consists of the properties and methods that you use to write applications
that access and manipulate existing databases. This includes facilities for
querying the database, navigating through its tables, performing updates, and
adding or deleting records.
If you are working exclusively with databases that have already been created by
another application, it is possible to create applications entirely within the DML
functionality. Understanding the DDL methods, however, will add to your
knowledge of database structure and make you a more flexible database
programmer
There are many ways of organizing databases. Among the most popular are
indexed sequential access method (ISAM) file systems, network-model
databases, hierarchical databases, and relational databases. These types of
databases differ not only in the way they physically manage the storage and
retrieval of data, but also in the conceptual models they present to the user and
programmer.
In recent years, the relational model has generally become the de facto standard
for database design. This is due both to the power of the relational model itself,
and because it provides a standard interface called Structured Query Language
(SQL) that allows many different database tools and products to work together
in a consistent and understandable way. The Microsoft Jet database engine is a
relational database engine.
The relational database model presents the data as a collection of tables. Instead
of modeling the relationships in the data according to the way that it is
physically stored, the structure is defined by establishing relations between
simple tables.

Database Normalization in VB in Visual basic

The task of the database designer is to structure the data in a way that
eliminates unnecessary duplication and provides a rapid search path to all
necessary information. The process of dividing the information into separate
tables that meet these goals is called normalization.
Normalization can be a complex process with many specific rules and different levels of normal form. For a complete discussion of the process one must refer to advanced books. However, normalizing most simple databases can be
accomplished by following a simple rule of thumb: tables that contain repeated information should be divided into separate tables to eliminate the duplication.

designates a field as a foreign key

If the foreign table's primary key consists of more than one field, you must use a multiple-field index definition, listing all of the referencing fields, the name of the foreign table, and the names of the referenced fields in the foreign table in the same order that the referencing fields are listed. If the referenced field or fields are the foreign table's primary key, you don't have to specify the referenced fields by default the Jet engine behaves as if the foreign table's primary key is the referenced fields.

designates one field or set of fields in a table as a primary key

All values in the primary key must be unique, and there can be only one
primary key for a table. If you set a PRIMARY KEY constraint on a table
that already has a primary key, an error occurs.

field as a unique key

This means that no two records in the table can have the same value in this field. You can constrain any field or list of fields as unique. If a multiple-field index is designated as a unique key, the combined values of all fields in the index must be unique, evenif two or more records have the same value in just one of the fields.

Using Visual Basic Variables in an SQL Statement

In a Visual Basic program, you can create a SELECT statement in your
application by concatenating local variables into the statement as needed to
select, sort, or filter the data as dictated by your application. For example, if you
have a TextBox control (TitleWanted) containing the name of a Title and you
want to fetch all books from the Titles table with this title, you can create an
SQL statement that includes the current value of the TextBox. Note that the
SQL query encloses the TitleWanted value in single quotation marks (' '):
Set Rst = Db.OpenRecordset("SELECT * FROM Titles " _
& " WHERE Title = '" & TitleWanted.T




The procedure for creating a new Jet database is simply a process of creating
and defining data access objects that correspond to the tables, fields, indexes,
and relations of your database design. In this overview, the process will be
presented step-by-step, followed by a complete code example for creating the
Biblio.mdb database.
The first step in creating a new database is to create the Database object itself,
and to define its structure by adding TableDef and Field objects that correspond
to your design.

To create a new database
1 Use the Dim statement to create new object variables for each object in your
database. In addition to the DBEngine and default Workspace objects that
make up the working environment, you will need:
One Database object
One TableDef object for each table
One Field object for each field in each table
One Index object for each index in each table
For example, to create object variables for the Biblio.mdb database, you could
use the following code:
Dim MyDB As Database, MyWs As Workspace
Dim AuTd As TableDef, TitTd As TableDef, _
PubTd As tableDef
Dim AuFlds(2) As Field, TitFlds(5) _
As Field, PubFlds(10) As Field
Dim AuIdx As Index, TitIdx(3) As Index, _
PubIdx As Index

2 Use the CreateDatabase method of the Workspace object to create the new
database. In this example, the method uses the minimum two arguments: one
to specify the database name, and one to specify the locale:
Set MyWs = DBEngine.Workspaces(0)
Set MyDb = MyWs.CreateDatabase("C:\VB\Biblio.mdb", _
dbLangGeneral, dbVersion30)

Note that the constant dbVersion30 specifies a Jet version 3.0 database. If you
use the dbVersion30 constant to create a version 3.0 database, only 32-bit
applications using the Jet version 3.0 engine or higher will be able to access it.
3 Use the CreateTableDef method of the Database object to create new
TableDef objects for each table in the database, as follows:
Set TitTd = MyDB.CreateTableDef("Titles")
Set AuTd = MyDB.CreateTableDef("Authors")
Set PubTd = MyDB.CreateTableDef("Publishers")

4 Use the CreateField method of the TableDef object to create new Field objects
for each field in the table, and to set properties of each field to define the
field's size, data type, and other needed attributes. For example, the following
code creates the Authors table in the Biblio.mdb database:
Set AuFlds(0) = AuTd.CreateField("Au_ID", dbLong)
' Make it a counter field.
AuFlds(0).Attributes = dbAutoIncrField
Set AuFlds(1) = MyTd.CreateField("Author", dbText)
AuFlds(1).Size = 50

5 Use the Append method to add each field to its table and each table to the
database, as shown in the following code:
AuTd.Fields.Append AuFlds(0)
AuTd.Fields.Append AuFlds(1)
MyDB.TableDefs.Append AuTd

Access from your application to a data source is through a connection ADO

The object model embodies the concept of a connection with the Connection object.

A transaction delimits the beginning and end of a series of data access operations
that transpire across a connection. ADO ensures that changes to a data source
resulting from operations in a transaction either all occur successfully, or not at all.
If you cancel the transaction or one of its operations fails, then the ultimate result
will be as if none of the operations in the transaction had occurred. The data source
will be as it was before the transaction began.

The object model does not explicitly embody the concept of a transaction, but
represents it with a set of Connection object methods.

ADO accesses data and services from OLE DB providers. The Connection object is
used to specify a particular provider and any parameters. For example, Remote
Data Service (RDS) can be invoked explicitly or it can be invoked implicitly with the
"MS Remote" provider.

Basic ADO Programming Model in Visual basic

ADO provides the means for you to perform the following sequence of actions:

1. Connect to a data source. Optionally, you can ensure that all changes to the
data source occur either successfully or not at all.

2. Specify a command to gain access to the data source, optionally with variable parameters, or optionally optimized for performance.

3. Execute the command.

4. If the command causes data to be returned in the form of rows in a table,
store the rows in a cache that you can easily examine, manipulate, or change.

5. If appropriate, update the data source with changes from the cache of rows.

6. Provide a general means to detect errors (usually as a result of making a
connection or executing a command).

Typically, you will employ all these steps in the programming model. However, it's
worth noting that ADO is flexible enough that you can do useful work by executing just part of the model. For example, you could store data from a file directly into a cache of rows, then use ADO resources merely to examine the data.

The RDS Object Model Summary in Visual basic

RDS.DataSpace





RDSServer.DataFactory







RDS.DataControl

Description
This object only contains a method to obtain a
server proxy. The proxy may be the default or a
custom server program (business object). The
server program may be invoked on the Internet, an
intranet, or local area network, or be a local
dynamic-link library.
This object represents the default server program.
It executes the default RDS data retrieval and
update behavior.
• This object can automatically invoke the
RDS.DataSpace and
RDSServer.DataFactory objects.

• Use this object to invoke the default RDS
data retrieval or update behavior.

• This object also provides the means for
visual controls to access the returned
Recordset object.

RDS Programming Model with Objects in VB Visual baisc

The goal of RDS is to gain access to and update data sources through an
intermediary like the Internet Information Server. The programming model
specifies the sequence of activities necessary to accomplish this goal. The object
model specifies the objects whose methods and properties affect the programming model.
RDS provides the means to perform the following sequence of actions:
13. Specify the program to be invoked on the server, and obtain a way (proxy) to
refer to it from the client. (RDS.DataSpace)

14. Invoke the server program. Pass parameters to the server program that
identify the data source and the command to issue. (proxy or
RDS.DataControl)

15. The server program obtains a Recordset object from the data source,
typically by using ADO. Optionally, the Recordset object is processed on the
server. (RDSServer.DataFactory)

16. The server program returns the final Recordset object to the client
application. (proxy)

17. On the client, the Recordset object is put into a form that can be easily used
by visual controls. (visual control and RDS.DataControl)

18. Changes to the Recordset object are sent back to the server and used to
update the data source. (RDS.DataControl or RDSServer.DataFactory)

Creatiung forms during Run Time in visual basic

Private Sub Command1_Click()
Dim x As New frmTest
x.Caption = "Test Form" & Forms.Count
x.Show
End Sub


Private Sub Command2_Click()
MsgBox "The Forms collection contains " & Forms.Count & " loaded forms."
End Sub


Private Sub Command3_Click()
Dim iLoop As Integer
For iLoop = Forms.Count - 1 To 0 Step -1
Unload Forms(iLoop)
Next iLoop
End Sub
Option Explicit

Private Sub Form_Load()

'Set the Drag icon of the control
'lstOrginal.DragIcon = imgList.ListImages("DRAG").ExtractIcon
End Sub

Private Sub lstDestination_DragDrop(Source As Control, X As Single, Y As Single)
If Source Is lstOrginal Then
If Source.ListIndex > -1 Then
lstDestination.AddItem Source.List(Source.ListIndex)
Source.RemoveItem Source.ListIndex
End If
End If
End Sub

Private Sub lstOrginal_MouseDown(Button As Integer, Shift As Integer, X As Single, Y
As Single)
lstOrginal.Drag vbBeginDrag
Private Sub lstOrginal_MouseUp(Button As Integer, Shift As Integer, X As Single, Y As
Single)

lstOrginal.Drag vbEndDrag

End Sub

Calling a DLL Procedure in visual baisc

Option Explicit

Private Declare Function GetComputerNameA Lib "kernel32" _
(ByVal lpBuffer As String, nSize As Long) As Long
Private Declare Function WNetGetUserA Lib "mpr" _
(ByVal lpName As String, ByVal lpUserName As String, lpnLength As Long) As
Long
Private Declare Function GetWinDir Lib "kernel32" Alias "GetWindowsDirectoryA" _
(ByVal lpBuffer As String, ByVal nSize As Long) As Long




Private Sub cmdGetComputerName_Click()
Dim strBuffer As String, lResult As Long
strBuffer = String(255, 0)
lResult = GetComputerNameA(strBuffer, Len(strBuffer))
If lResult <> 0 Then
strBuffer = Left(strBuffer, InStr(strBuffer, vbNullChar) - 1)
txtGetComputerName.Text = strBuffer
End If
End Sub


Private Sub cmdGetUserName_Click()
Dim strUserName As String, lResult As Long
strUserName = String(255, 0)
lResult = WNetGetUserA(vbNullString, strUserName, Len(strUserName))
If lResult = 0 Then
strUserName = Left$(strUserName, InStr(strUserName, vbNullChar) - 1)
txtGetUserName.Text = strUserName
End If


End Sub


Private Sub cmdGetWindowsDirectory_Click()
Dim strWindowsDir As String, lResult As Long
strWindowsDir = String(255, 0)
lResult = GetWinDir(strWindowsDir, Len(strWindowsDir))
strWindowsDir = Left$(strWindowsDir, lResult)
txtGetWindowsDirectory.Text = strWindowsDir
End Sub
Figure 3a
Option Explicit

Private Declare Function GetComputerNameA Lib "kernel32" _
(ByVal lpBuffer As String, nSize As Long) As Long
Private Declare Function WNetGetUserA Lib "mpr" _
(ByVal lpName As String, ByVal lpUserName As String, lpnLength As Long) As
Long
Private Declare Function GetWinDir Lib "kernel32" Alias "GetWindowsDirectoryA" _
(ByVal lpBuffer As String, ByVal nSize As Long) As Long




Private Sub cmdGetComputerName_Click()
Dim strBuffer As String, lResult As Long
strBuffer = String(255, 0)
lResult = GetComputerNameA(strBuffer, Len(strBuffer))
If lResult <> 0 Then
strBuffer = Left(strBuffer, InStr(strBuffer, vbNullChar) - 1)
txtGetComputerName.Text = strBuffer
End If
End Sub


Private Sub cmdGetUserName_Click()
Dim strUserName As String, lResult As Long
strUserName = String(255, 0)
lResult = WNetGetUserA(vbNullString, strUserName, Len(strUserName))
If lResult = 0 Then
strUserName = Left$(strUserName, InStr(strUserName, vbNullChar) - 1)
txtGetUserName.Text = strUserName
End If
End Sub


Private Sub cmdGetWindowsDirectory_Click()
Dim strWindowsDir As String, lResult As Long
strWindowsDir = String(255, 0)
lResult = GetWinDir(strWindowsDir, Len(strWindowsDir))
strWindowsDir = Left$(strWindowsDir, lResult)
txtGetWindowsDirectory.Text = strWindowsDir
End Sub

Project using ImageList Control in visual basic

Option Explicit

Private Sub cmdLoadBitmap_Click()

If Val(txtBitmaps) = 0 Then

MsgBox "Enter a number between 1 and 9."

txtBitmaps.SetFocus

Exit Sub

End If

Image2.Picture = imgBitmaps.ListImages(Val(txtBitmaps)).Picture

End Sub

Private Sub cmdLoadIcon_Click()

If Val(txtIcons) = 0 Then

MsgBox "Enter a number between 1 and 9."

txtIcons.SetFocus

Exit Sub

End If

Image1.Picture = imgIcons.ListImages(Val(txtIcons)).Picture

End Sub

Visual Basic-6 has emerged as one of the standard Windows Programming Language and it has become a must for all Software people for developing Applications in Visual Environment. So it is, one must learn Visual Basic-6.

What is our Objective in this Courseware?


The Overall Objective in this Courseware is to give a Hands-on Approach to develop different projects in Visual Basic-6.0 using intrinsic, professional and user–created ActiveX controls and also develop projects using databases, DAO’s, ADO’s, DLL’s, Documents, Crystal Reports etc. covering almost all the essential features of VB-6 Professional Edition. After reading one lesson any interested reader will be able to get complete hands-on experience with the VB project and get a sense of fulfilment and achievement. Learning by doing is the motto with which this courseware is written. After giving a short introduction about VB-6 we will explain how to create and execute a project in VB using some intrinsic ActiveX controls. Creating and executing projects will be the central theme of all the lessons which we will be giving in this courseware.

What is Visual Basic-6?


Visual Basic-6 has its origin in Basic which was developed round about the year 1960, when high level languages were just being introduced to the computer community. Microsoft has made it extremely powerful by gearing all its good features to the Windows environment. Starting with the version 3 and then with 4, and then with 6, Visual Basic is now at version 6. Basic is a Procedure Oriented Language intended to implement single tasks in text based environment whereas Visual Basic is an Event Driven Language intended to implement Projects or Applications containing multiple tasks in Windows Environment.

What can Visual Basic do for you?

Visual Basic can serve as an ideal front end tool for the clients to interact. It has got connectivity mechanisms for all types of databases situated far and wide in a network and so it can cater to the needs of a large body of clients. Using the latest ActiveX technologies, it can integrate the functionalities provided by other applications like Word Excel and other Windows. Its internet capabilities provide easy access to documents and applications across the internet. Above all it embodies the Object Oriented Technology, which is the cutting edge technology for all the present day developments in the Software World. The final application is a true EXE file and so can be freely distributed.


Structure of VB-6 Projects:


We said earlier that VB-6 implements projects or applications. A project is developed using one or more Forms. A Form is simply a window containing one or more Controls. Controls in VB consist of labels, text boxes, list boxes, combo boxes, scroll bars etc. which are the constituents of windows environment. It is only the controls that give VB, its immense power and so there is a lot of interest in creating more and more powerful controls. ActiveX controls mark a significant development in controls technology. In fact all controls in VB-6 are ActiveX controls, which have the extension .ocx. These controls have properties whose values can be initialized at design time and also varied during run time. The properties are something like variables. The controls are activated by codes written in a high level language. By associating our problem variables with the properties of the controls, our problem variables can be manipulated to give the problem solution. In summary we can say that a VB project is made of forms, controls and their properties and codes.

Integrated Development Environment:

The working environment in VB is often referred to as the Integrated Development Environment or IDE, because it integrates many different functions such as design, editing, compiling and debugging within a common environment. Since all our projects are developed only in the IDE, let us now have a brief look at its features. You will be able to understand their uses at the time of building projects. The VB IDE looks as shown in the figure.