View
215
Download
0
Category
Preview:
Citation preview
7/30/2019 vb-6ch123-110721032904-phpapp01
1/25
3 Cube Computer InstituteVB 6 Notes
Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh
- 1 -
CHAPTER 1
Introduction to Visual Basic 6.0
Visual basic is a high level programming language (HLL) developed from the BASIC programminglanguage.
VB programming is done in a graphical environment, also known as GUI (Graphical User Interface).Visual Basic enables the user to design the user interface quickly by drawing and arranging the userelements. The Window GUI defines how the various elements such as FORMS and CONTROLS lookand function.Visual Basic is an event-driven programming language.
Procedural vs. OOP vs. event-driven programming language
In the Procedural languages such as Basic, C, COBOL, etc the program specifies exact sequence of alloperations. Program logic determines the next instruction to execute in response to conditions anduser request.
OOPs define software as a collection of discrete oblects that specify both data structure and behavior.
OOPs Identify following aspects: Data abstraction, Inheritence, Polymorphism, Encapsulation(information hiding)etc.
Event Driven Programming:
Events are the actions that are performed by the user during the application usage. If a user clicks amouse button on any object then the Click event occurs. If a user moves the mouse then the mousemove event occursAny programming language, which uses these events to run a specific portion of the program, will becalled event driver programming. The GUI based programs are all developed using event driverprogramming.In the event driven model programs are no longer procedural; the do not follow a sequential logic.The programmers do not take control and determine the sequence of execution of program. Instead,the user can press and click on various button and boxes in a window. Each user action can cause an
event to occur, which triggers a Basic procedure (code) that you have written.
The Object model in VB 6:
In VB you will work with Objects, which have Properties and methods.OBJECTS:Think of an Object as a thing. Examples of Objects are Forms and Controls. Forms are the windowsand dialog boxes you place on the screen; Controls are the elements you place inside a form, such astext coxes, command button, etc.
Properties:Properties tell something about the Object, such as its name, color, size, etc or how it will behave. Torefer to a property of an Object, VB syntax is:
Object.PropertyFor example, to refer to text property of Text Box named text1, we use text1.Text
Methods:Actions associated with the objects are called Methods. Example: Move, Print, Resize, Clear.
7/30/2019 vb-6ch123-110721032904-phpapp01
2/25
3 Cube Computer InstituteVB 6 Notes
Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh
- 2 -
VB6 Environment / IDE (Integrated Development Environment)
The VB6 environment is where you create and test your projects. Fig 2 shows various windows in
VB6 environment. Each window can be moved, resized, opened, or closed.Various windows in VB6 environment are:Main VB Window
The main VB Window holds the VB Menu bar, the toolbar, and the form location and size informationFORM WINDOW
The form window is where you design the forms that makes up your user interface. When you begina new project, VB gives your form name the default name Form1.The Project Explorer WindowThis window holds the filenames for the files included in your project.
Fig 3: Project Explorer WindowThe Properties Window
We use the properties window to set the properties for the objects in the project.The Form Layout Window
The position of the form in this window determines the position of the form on the desktop whenexecution of the project begins.The Toolbox
Toolbox window contains a set of controls which are used to customize forms. Using this controls
user can create an interface between user and the applicationFigure 4 Toolbox windows with its controls available commonly.
7/30/2019 vb-6ch123-110721032904-phpapp01
3/25
3 Cube Computer InstituteVB 6 Notes
Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh
- 3 -
Control Description
Pointer used to interact with the controls on the form
PictureBox used to display images
TextBox used to accept user input which can display only editable text
Frame used to group other controls
CommandButton used to initiate an action by pressing on the button
CheckBox used to do a choice for user (checked or unchecked)
OptionButton used in groups where one at a time can be true
ListBox used to provide a list of items
ComboBox used to provide a short list of items
HScrollBar a horizontal scrollbar
VScrollBar a vertical scrollbar
Timer used to perform tasks in specified intervals.
DriveListBox used to access to the system drives
DirListBox used to access to the directories on the system
FileListBox used to access to the files in the directory
Shape used to draw circles, rectangles, squares, ellipses
Line used to draw lines
Image used to display images. But less capability than the PictureBoxData used to connect a database
OLE used to interact with other windows applications
Label used to display texts which cannot be edited
The Toolbar
We can use the buttons on the toolbar for frequently used operations.
7/30/2019 vb-6ch123-110721032904-phpapp01
4/25
3 Cube Computer InstituteVB 6 Notes
Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh
- 4 -
WORKING MODES IN VISUAL BASIC
VB has 3 distinct modes:Design mode
While you are designing the user interface and writing code, you are in design mode.Runtime mode
When you are testing and running your project, you are in runtime mode.
Break ModeIf you get a run-time error or pause project execution, you are in break time mode.
VISUAL BASIC CODE STATEMENTS
The basic program in VB requires 3 statements:1.The Remark Statements
Remark statements are sometimes called as COMMENTS, are used for project documentation only.They are not considered executable and have no effect when the project runs. The purpose ofremarks is to make the project more readable and understandable by the person who reads it.VB remarks begin with an apostrophe.
Example:
this project is made in VB6Exit the projectText1.Text=Welcome setthe text property of text1 to welcome.
2. The Assignment Statements
The assignments statement assigns a value to a property or variable.Syntax:[Let] Object.Property = valueThe LET is optional and may be included if you wish.Example:Text1.Text=welcomeLet lblName = ABCLblname.FontSize = 12
3. The END statement
The END statement stops execution of the project. Example, Include an END statement in the subprocedure for an EXIT button
FIRST VB PROJECT
Getting started
To open the Visual Basic environment and to work with it select and click on Microsoft Visual Basic6.0 in the start menu. When Visual Basic is loaded the New Project dialog shown in figure 1.1 will bedisplayed with the types available in Visual Basic. You can notice that Standard Exe is highlighted bydefault. Standard Exe allows the user to create standard executable. Standard executable is a typewhich has most of the common features of Visual basic
7/30/2019 vb-6ch123-110721032904-phpapp01
5/25
3 Cube Computer InstituteVB 6 Notes
Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh
- 5 -
Design the FORM
7/30/2019 vb-6ch123-110721032904-phpapp01
6/25
3 Cube Computer InstituteVB 6 Notes
Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh
- 6 -
Setting the Property
Object Property Value
Form1 Name Form1
Caption Form1
Command1 Name cmdOK
Caption OK
Command2 Name cmdExitCaption Exit
Text1 Name txtName
Text
CodePrivate Sub cmdExit_Click()txtName.Text = "Welcome to VB 6"End SubPrivate Sub cmdOK_Click()EndEnd Sub
Run The Project
Press F5 or Start button on the toolbar to run the project.
Save the project
While saving the project,The Project file is saved with extension .vbp
The form file is saved with extension .frm
The module file is saved with extension .bas
The custom controls is saved with extension .ocx
Naming Rules and Convention for Object:
Naming Rules:
When you select names for object, VB requires the name to begin with a letter.The name can be up to 40 characters in length and can contain letter, digits and underscore.An object name cannot include a space or punctuation marks.
The naming ConventionAlways begin a name with lowercase 3 letter prefix, which identifies the object type (such aslabel, command button, etc.) and capitalize the first character after the prefix( the real nameof the object).For names with multiple words, capitalize each word in the name.All names must be meaningful and indicate the purpose of the Object.Example: lblMessage, cmdOk, cmdExit, lblDiscountRate, etc.
Object naming conversions of controls (prefix)
Form -frmLabel -lblTextBox -txtCommandButton -cmd
CheckBox -chkOptionButton -optComboBox -cboListBox -lstFrame -fmePictureBox -picImage -imgShape -shpLine -lin
7/30/2019 vb-6ch123-110721032904-phpapp01
7/25
3 Cube Computer InstituteVB 6 Notes
Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh
- 7 -
HScrollBar -hsbVScrollBar -vsb
TYPES OF ERRORS
1. COMPILE ERRORSThe VB attempts to convert your program code to machine language (called compiling the
code) ,it finds any compile errors .You get the compile errors when you break the syntax rules ofVisual basics and sometimes when you use an illegal object or property.For example, try spelling end as ennd.
txtName.Text=ABC is correct but txt,name=ABC is incorrect.2. RUN-TIME ERRORSIf your projects halts during execution, thats run time errors. VB displays a dialog box and goes intobreak mode and highlights the statement causing the error.Statements that cannot be executed correctly causes runtime errors. Such statements are compiledcorrectly but fail too execute.Examples: calculation with non-numeric value, divide by zero, square of negative number.3. LOGICAL ERRORSWith logic errors, a project run but produces incorrect results. Example, result of a calculation isincorrect or the wrong text appears or the text is OK but appears in the wrong location.
CONTEXT SENSITIVE HELP
VB 6 provides a great HELP section, if MSDN Library is installed in your machine. For ContextSensitive Help, select a VB object, such as Text Boxes, or place the insertion point in a word in theeditor and Press F1. The MSDN Library viewer will open on the correct page, if possible, saving you asearch.
7/30/2019 vb-6ch123-110721032904-phpapp01
8/25
3 Cube Computer InstituteVB 6 Notes
Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh
- 8 -
CHAPTER 2
More Controls
In this chapter we will be discussing about various controls in VB6.
LABEL CONTROL:A label control displays text that the user cannot directly change.You can use labels to identify controls, such as text boxes and scroll bars that do not have their ownCaption property.
Example: lblName.Caption=ABCThe actual text displayed in a label is controlled by the Caption property, which can be set at designtime in the Properties window or at run time by assigning it in code.To clear a Labels caption:
lblMessage.Caption=
TEXT CONTROL:
Text boxes are versatile controls that can be used to get input from the user or to display text. Textboxes should not be used to display text that you don't want the user to change, unless you've set the
Locked property to True.The actual text displayed in a text box is controlled by the Textproperty.It can be set in three different ways:
1. at design time in the Property window,2. at run time by setting it in code,
example: txtMessage.text=Welcome3. by input from the user at run time.
The current contents of a text box can be retrieved at run time by reading the Textproperty.
Multiple-Line Text Boxes and Word Wrap
By default, a text box displays a single line of text and does not display scroll bars. If the text is longerthan the available space, only part of the text will be visible. The look and behavior of a text box can
be changed by setting two properties, MultiLine and ScrollBars, which are available only at designtime.Note The ScrollBars property should not be confused with scroll bar controls, which are notattached to text boxes and have their own set of properties.Setting MultiLine to True enables a text box to accept or display multiple lines of text at run time.Alignment Property of Text BoxYou must set the Multiline property to true or VB ignores the alignment.
The values of alignment property, which can be set at Design time (not at run time), are:0 Left Justify 1 Right Justify 2 CenterTo clear a text box at runtime:
txtMessage.Text=
FRAMESFrame controls are used to provide an identifiable grouping for other controls. For example, you canuse frame controls to subdivide a form functionally to separate groups of option button controls.In most cases, you will use the frame control passively to group other controls and will have noneed to respond to its events. You will, however, most likely change its Name, Caption, or Fontproperties.
Adding a Frame Control to a Form
When using the frame control to group other controls, first draw the frame control, and then drawthe controls inside of it. This enables you to move the frame and the controls it contains together.
7/30/2019 vb-6ch123-110721032904-phpapp01
9/25
3 Cube Computer InstituteVB 6 Notes
Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh
- 9 -
Drawing Controls inside the Frame
To add other controls to the frame, draw them inside the frame. If you draw a control outside theframe, or use the double-click method to add a control to a form, and then try to move it inside theframe control, the control will be on top of the frame and you'll have to move the frame and controlsseparately.Note If you have existing controls that you want to group in a frame, you can select all the controls,
cut them to the clipboard, select the frame control, and then paste them into the frame control.
CHECK BOX
Checkboxes allow the user to select (or deselect) an option.In any group of checkboxes, any number may be selected.The value property of a check box is set to 0 if Unchecked (default), 1 if Checked, and 2 if Grayed(dimmed).
Example: chkDiscount.Value=0 UncheckedchkDiscount.Value=1 checked
chkDiscount.Value=2 grayed
chkDiscount.Value=checked
chkDiscount.Value=unchecked
OPTION BUTTONS:
Option buttons present a set of two or more choices to the user.Unlike check boxes, however, option buttons should always work as part of a group; selecting oneoption button immediately clears all the other buttons in the group.Defining an option button group tells the user, "Here is a set of choices from which you can chooseone and only one.Creating Option Button Groups
All of the option buttons placed directly on a form (that is, not in a frame or picture box) constituteone group. If you want to create additional option button groups, you must place some of them insideframes or picture boxes.All the option buttons inside any given frame constitute a separate group.Selecting or Disabling Option Buttons
An option button can be selected by:Clicking it at run time with the mouse.Tabbing to the option button group and then using the arrow keys to select an option button withinthe group.Assigning its Value property to True in code:
optChoice.Value = True or optChoice.Value = False
To make a button the default in an option button group, set its Value property to True at designtime. It remains selected until a user selects a different option button or code changes it.
Images Control:
The image control is used only for displaying pictures.Pictures are loaded into the image control just as they are in the picture box: at design time, set the
Pictureproperty to a file name and path; at run time, use the
LoadPicturefunction.
It has a Stretch property while the picture box has anAutoSize property. Setting theAutoSizeproperty to True causes a picture box to resize to the dimensions of the picture; setting it to Falsecauses the picture to be cropped (only a portion of the picture is visible).You can set the Visible property to TRUE to make the image invisible.Example: imgLogo.Visible=False
SHAPE CONTROL
The shape control is used to create the following predefined shapes on forms, frames, or pictureboxes: rectangle, square, oval, circle, rounded rectangle, or rounded square.
7/30/2019 vb-6ch123-110721032904-phpapp01
10/25
3 Cube Computer InstituteVB 6 Notes
Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh
- 10 -
Predefined Shapes
The Shape property ofthe shape control provides you with six predefined shapes. The followingtable lists all the predefined shapes, their values and equivalent Visual Basic constants:
Shape Style Constant
Rectangle 0 vbShapeRectangle
Square 1 vbShapeSquare
Oval 2 vbShapeOval
Circle 3 vbShapeCircle
Rounded Rectangle 4 vbShapeRoundedRectangle
Rounded Square 5 vbShapeRoundedSquare
LINE CONTROL
The line control is used to create simple line segments on a form, a frame, or in a picture box.
You can control the position, length, color, and style of line controls to customize the look ofapplications.
CHANGING FONT PROPERTIES OF CONTROLS
At design time use the Fontproperty to open Font dialog.At runtime we use FontObject. A font object has several properties including Name, size, Bold, Italic,Underline, etc.Example:
Object.Font.Bold=True
Object.Font.Italic=True
Object.Font.UnderLine=True
Object.Font.Size=12
CHANGING COLOR PROPERTIES OF CONTROLS
At designtime we can use ForeColor property to change the color of text/caption in control.At runtime we can use ForeColor property.The VB6 provides 8 color constants to use:vbBlack, vbRed, vbGreen, vbYellow, vbBlue, vbMagenta, vbCyan, vbWhite
Example:txtName.ForeColor=vbRed
lblMessage.ForeColor=vbGreen
7/30/2019 vb-6ch123-110721032904-phpapp01
11/25
3 Cube Computer InstituteVB 6 Notes
Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh
- 11 -
CHECK BOX AND OPTION BUTTON EXAMPLE
Private Sub chkBold_Click()Text1.Font.Bold = TrueEnd SubPrivate Sub chkItalic_Click()Text1.Font.Italic = TrueEnd SubPrivate Sub chkUnderline_Click()Text1.Font.Underline = True
End SubPrivate Sub optRed_Click()Text1.ForeColor = vbRedEnd SubPrivate Sub optGreen_Click()Text1.ForeColor = vbGreenEnd SubPrivate Sub optBlue_Click()Text1.ForeColor = vbBlueEnd Sub
7/30/2019 vb-6ch123-110721032904-phpapp01
12/25
3 Cube Computer InstituteVB 6 Notes
Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh
- 12 -
SHAPE CONTROL EXAMPLE
Private Sub cmdRectangle_Click()Shape1.Shape = 0End SubPrivate Sub cmdSquare_Click()Shape1.Shape = 1End SubPrivate Sub Oval_Click()Shape1.Shape = 2End SubPrivate Sub cmdCircle_Click()Shape1.Shape = 3End Sub
Private Sub cmdRoundedRectangle_Click()Shape1.Shape = 4End SubPrivate Sub cmdRoundedSquare_Click()Shape1.Shape = 5End Sub
DEFINING KEYBOARD ACCESS KEYS
Many people prefer to use the keyboard, rather than a mouse, for most operations.You can make your program respond to keyboard by defining access keys.
For example: In the below diagram, you can select the OK button by pressing alt+o and theexit button by pressing alt+e.
7/30/2019 vb-6ch123-110721032904-phpapp01
13/25
3 Cube Computer InstituteVB 6 Notes
Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh
- 13 -
We can set access keys for command button, option buttons and check boxes. When you define theirCaption property. Type an ampersand (&) in front of the character you want for the access key; VBunderlines the character.
For example:
&OK for OK
E&xit for Exit
Specifying the Default and Cancel Properties
On each form, you can select a command button to be the default command button that is,whenever the user presses the ENTER key the command button is clicked regardless of which othercontrol on the form has the focus. To specify a command button as default set the Defaultproperty toTrue.You can also specify a cancel button. When the Cancel property of a command button is set to True,it will be clicked whenever the user presses the ESC key, regardless of which other control on theform has the focus.
Setting the Tab Order
The tab order is the order in which a user moves from one control to another by pressing the TABkey. Each form has its own tab order. Usually, the tab order is the same as the order in which you
created the controls.For example, assume you create two text boxes, Text1 and Text2, and then a command button,Command1. When the application starts, Text1 has the focus. Pressing TAB moves the focus betweencontrols in the order they were createdTo change the tab order for a control, set the TabIndex property. The TabIndex property of acontrol determines where it is positioned in the tab order. By default, the first control drawn has aTabIndex value of 0, the second has a TabIndex of 1, and so on. When you change a control's taborder position, Visual Basic automatically renumbers the tab order positions of the other controls toreflect insertions and deletions. For example, if you make Command1 first in the tab order, theTabIndex values for the other controls are automatically adjusted upward, as shown in the followingtable.
ControlTabIndex before it is changed TabIndex after it is changed
Text1 0 1
Text2 1 2
Command1 2 0
The highestTabIndex setting is always one less than the number of controls in the tab order(because numbering starts at 0). Even if you set the TabIndex property to a number higher than thenumber of controls, Visual Basic converts the value back to the number of controls minus 1.Note Controls that cannot get the focus, as well as disabled and invisible controls, don't have aTabIndex property and are not included in the tab order. As a user presses the TAB key, thesecontrols are skipped.Removing a Control from the Tab Order
Usually, pressing TAB at run time selects each control in the tab order. You can remove a controlfrom the tab order by setting its TabStop property to False (0).A control whose TabStop property has been set to False still maintains its position in the actual taborder, even though the control is skipped when you cycle through the controls with the TAB key.
CREATING TOOLTIPS
The word or short phrase that describes the function of a toolbar button or other tool. The ToolTipappears when you pause the mouse pointer over an object.
7/30/2019 vb-6ch123-110721032904-phpapp01
14/25
3 Cube Computer InstituteVB 6 Notes
Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh
- 14 -
ToolTipTextPropertyReturns or sets aToolTip.Atdesign timeyou can set the ToolTipTextproperty string in the control's properties dialog box.
At Run-time:object.ToolTipText [= string]
The ToolTipText property syntax has these parts:
Part Description
object An object expression that evaluates to an object in the Applies To list.
string A string associated with an object in the Applies To list. that appearsin a small rectangle below the object when the user's cursor hoversover the object at run time for about one second.
With Statement
Executes a series of statements on a single object or a user-defined type.Syntax
With object
[statements]
End WithThe With statement syntax has these parts:
Part Description
object Required. Name of an object or a user-defined type.
statements Optional. One or more statements to be executed on object.
Remarks
The With statement allows you to perform a series of statements on a specified object withoutrequalifying the name of the object. For example, to change a number of differentpropertieson asingle object, place the property assignment statements within the With control structure, referringto the object once instead of referring to it with each property assignment. The following exampleillustrates use of the With statement to assign values to several properties of the same object.
With MyLabel
.Height = 2000
.Width = 2000
.Caption = "This is MyLabel"
End With
Note Once a With block is entered, object can't be changed. As a result, you can't use a single Withstatement to affect a number of different objects.
Concatenating Strings:
Used to force string concatenation of twoexpressions.Syntax
http://alink_4.click%28%29/http://alink_4.click%28%29/http://alink_4.click%28%29/http://alink_7.click%28%29/http://alink_7.click%28%29/http://alink_7.click%28%29/http://alink_6.click%28%29/http://alink_6.click%28%29/http://alink_6.click%28%29/http://alink_4.click%28%29/http://alink_4.click%28%29/http://alink_4.click%28%29/http://alink_4.click%28%29/http://alink_6.click%28%29/http://alink_7.click%28%29/http://alink_4.click%28%29/7/30/2019 vb-6ch123-110721032904-phpapp01
15/25
3 Cube Computer InstituteVB 6 Notes
Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh
- 15 -
result = expression1 & expression2
The & operator syntax has these parts:
Part Description
result Required; anyStringorVariantvariable.
expression1 Required; any expression.
expression2 Required; any expression.
Example:
txtOutPut.Text= Welcome & To VB 6txtName.Text= txtFirstName.Text & & txtLastName.Text
Remarks
If an expression is not a string, it is converted to a String variant. Thedata typeof result is String ifboth expressions arestring expressions; otherwise, result is a String variant. If both expressions areNull, result is Null. However, if only one expression is Null, that expression is treated as a zero-lengthstring ("") when concatenated with the other expression. Any expression that isEmptyis also treatedas a zero-length string.
http://alink_5.click%28%29/http://alink_5.click%28%29/http://alink_5.click%28%29/http://alink_6.click%28%29/http://alink_6.click%28%29/http://alink_7.click%28%29/http://alink_7.click%28%29/http://alink_7.click%28%29/http://alink_8.click%28%29/http://alink_8.click%28%29/http://alink_8.click%28%29/http://alink_9.click%28%29/http://alink_9.click%28%29/http://alink_9.click%28%29/http://alink_10.click%28%29/http://alink_10.click%28%29/http://alink_11.click%28%29/http://alink_11.click%28%29/http://alink_11.click%28%29/http://alink_11.click%28%29/http://alink_10.click%28%29/http://alink_9.click%28%29/http://alink_8.click%28%29/http://alink_7.click%28%29/http://alink_6.click%28%29/http://alink_5.click%28%29/7/30/2019 vb-6ch123-110721032904-phpapp01
16/25
3 Cube Computer InstituteVB 6 Notes
Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh
- 16 -
CHAPTER 3
Variables, Constants and Calculations
Variables and Constants
Memory locations that hold data that can be changed during project execution are called Variables.Memory locations that hold data that cannot be changed during project execution are called
Variables.For example,Variable: a customers name will vary as the information for each individual is being processed.Constant: However the name of the company and the sales tax rate will remain the same.
Identifier:
When you declare a variable or named constant, VB reserves an area of memory and assigns it aname, called an Identifier.
Data types in visual basic 6.0
The data type of a variable or constant indicates what type of information will be stored in theallocated memory space.The default data type is Variant.
If you do not specify a data type, your variables and constant will be Variants.Advantages & Disadvantages of using Variant data type:
Advantages Disadvantages
1.Its easy2. variables and constants change theirappearance as needed for each situation.
1. Less efficient than other data types, i.e., theyrequire more memory space and operate lessquickly than other data types.
The best practice is always specify the data types.Other data types are:
1. Numeric
Byte Store integer values in the range of 0 - 255
Integer Store integer values in the range of (-32,768) - (+ 32,767)
Long Store integer values in the range of (- 2,147,483,468) - (+ 2,147,483,468)
Single Store floating point value in the range of (-3.4x10-38) - (+ 3.4x1038)
Double Store large floating value which exceeding the single data type value
Currencystore monetary values. It supports 4 digits to the right of decimal point and15 digits to the left
2. String
Use to store alphanumeric values. A variable length string can store approximately 4 billioncharacters3. Date
Use to store date and time values. A variable declared as date type can store both date and timevalues and it can store date values 01/01/0100 up to 12/31/9999
4. BooleanBoolean data types hold either a true or false value. These are not stored as numeric values andcannot be used as such. Values are internally stored as -1 (True) and 0 (False) and any non-zerovalue is considered as true.
Naming rules and convention in VB 6.0
These are the rules to follow when naming elements in VB - variables, constants, controls,procedures, and so on:
7/30/2019 vb-6ch123-110721032904-phpapp01
17/25
3 Cube Computer InstituteVB 6 Notes
Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh
- 17 -
* A name must begin with a letter.* May be as much as 255 characters long* Must not contain a space or an embedded period or type-declaration characters used toype; these are ! # % $ & @* Must not be a reserved word (that is part of the code, like Option, for example)* The dash, although legal, should be avoided because it may be confused with the minus
sign. Instead of First-name use First_name or FirstName.* use a three letter prefix to append the name while declaring it.Examples: data type and their prefixes:
bln Boolean
cur Currency
dbl Double-precision floating point
dtm Date/ time
int Integer
lng Long Integer
sng Single
str String
vnt Variant
Variables:Variables are the memory locations which are used to store values temporarily. A defined namingstrategy has to be followed while naming a variable. A variable name must begin with an alphabetletter and should not exceed 255 characters. It must be unique within the same scope. It should notcontain any special character like %, &, !, #, @ or $.Declaring variables
To declare a variable, we use DIM statement.DIM statement General Form:
Dim identifier [as DataType]
If you omit the optional data type, the variables type defaults to variant.Example:
Dim vntChangingDim strName as String
Dim intTotal as IntegerThe reserved word Dim is really short for Dimension, which means size. When you declare avariable, the amount of memory reserved depends on its data types.
Data Type Numer of Bytes of Memory Allocated
Boolean 2
Byte 1
Currency 8
Date 8
Double 8
Integer 2
Long 4
Single 4
String (Variable Length) 10 bytes plus 1 byte for each character in thestring
Variant Holding Numbers 16 bytesHolding Characters 22 bytes plus 1 byte foreach character in the string
7/30/2019 vb-6ch123-110721032904-phpapp01
18/25
3 Cube Computer InstituteVB 6 Notes
Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh
- 18 -
SCOPE OF VARIABLES
The visibility of a variable is referred to as its Scope. Visibility means this variable can be seen orused in this locationThe scope is said to be global, module level or local.Global variable
A global variable may be used in all procedures of a project. To indicate a global level
variable, place a prefix of g before the identifier.Example: gintTotalSumModule level variable
Module level variables are accessible from all the procedure of a form. To indicate a modulelevel variable, place a prefix of m before the identifier.We place the module level variables and constants in the General Decalaration section of the form.
Example:______________________________Option ExplicitDim mintTotal as Integer______________________________Private sub cmdSum_click()mintTotal=text1.text + text2.text
End sub_______________________________Private sub cmdTotal_click()
mintTotal= mintTotal * 0.10End sub________________________________
Local variable
A local variable may be used only within the procedure in which it is defined. Any variablethat you declare inside a procedure is local in scope; it is known to that procedure.Example:
Private sub cmdSum_click()Dim intNum as IntegerDim curPrice as Integer
Dim blnCounter as BooleanEnd sub
Constant Named and Intrinsic
Constant provide a way to use words to describe a value that doesntchange.Constant can be Named or Intrinsic.
1. Named Constant:
The constant that you define for yourself are called Named Constants. We give the constant a name, adata type and a value. Once a value is decaled as a constant, its value cannot be changed duringprogram execution.The data type and the data type of the value must match for a constant.We declare named constant using the keyword Const.
General Form:Const Identifier [ As DataType ] = Value
Example:Const strAddress As String = Malad Const curSalesTaxRate as Currency = 0.08
Assigning Values to Constant
String Literals
String constants are called String literals and may contain letters, digits and special characters, suchas $#@%&*.Also, to declare a constant such as
7/30/2019 vb-6ch123-110721032904-phpapp01
19/25
3 Cube Computer InstituteVB 6 Notes
Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh
- 19 -
He said, I liked it , it are declared asConst strName as String=He said, I liked it
Numeric Constants
Numeric constants may contain only the digits (0-9), a decimalPoint and a sign(+ or -) at the left side. We cannot include a comma, dollar sign, any other special
character, or a sign at the right side.Data Type Constant value Example
Integer 1252170
Single or Currency 101.25-5.2
String literals VB103She said Hello.
2. Intrinsic Constant
Intrinsic constant are system-defined constants. Several sets of Intrinsic constants are stored inlibrary files and available for use in VB programs.
Intrinsic constants use a 2-charater prefix to indicate the source, such asVb for Visual basic, db for Access Objects and xl for Excel.
Example: vbRed, vbGreen, etc.
Operators in Visual Basic
Arithmetical Operators
Operators Description Example Result
+ Add 5+5 10
- Substract 10-5 5
/ Divide 25/5 5
\ Integer Division 20\3 6
* Multiply 5*4 20
^ Exponent (power of) 3^3 27
Mod Remainder of division 20 Mod 6 2
& String concatenation "George"&" "&"Bush" "George Bush"
Relational Operators
Operators Description Example Result
> Greater than 10>8 True
< Less than 10>8 False
>= Greater than or equal to 20>=10 True
7/30/2019 vb-6ch123-110721032904-phpapp01
20/25
3 Cube Computer InstituteVB 6 Notes
Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh
- 20 -
7/30/2019 vb-6ch123-110721032904-phpapp01
21/25
3 Cube Computer InstituteVB 6 Notes
Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh
- 21 -
CALCULATOR PROGRAM
Code:Private Sub cmdAdd_Click()
txtOutput.Text = Val(txtNum1.Text) + Val(txtNum2.Text)End Sub
Private Sub cmdDifference_Click()txtOutput.Text = Val(txtNum1.Text) - Val(txtNum2.Text)End Sub
Private Sub cmdMultiply_Click()txtOutput.Text = Val(txtNum1.Text) * Val(txtNum2.Text)End Sub
Private Sub Command4_Click()txtOutput.Text = Val(txtNum1.Text) / Val(txtNum2.Text)
End Sub
FORMATTING DATA
Use the formatting functions to format the data.To format means to control the way the output look.For example, 12 is just a number but $12.00 conveys more meaning for dollar amount.
VB 6 introduces 4 new formatting functions 1. FormatCurrency
FormatCurrency Returns an expression formatted as a number with a leading currency
symbol ($)Simple Form
FormatCurrency (Expression)General Form
FormatCurrency (Expression[,NumDigitsAfterDecimal [,IncludeLeadingDigit[,UseParensForNegativeNumbers [,GroupDigits]]]])
2. FormatNumber
FormatNumber Returns an expression formatted as a number
7/30/2019 vb-6ch123-110721032904-phpapp01
22/25
3 Cube Computer InstituteVB 6 Notes
Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh
- 22 -
Simple Form
FormatNumber(Expression)General Form
FormatNumber(Expression[,NumDigitsAfterDecimal [,IncludeLeadingDigit[,UseParensForNegativeNumbers [,GroupDigits]]]])
3. FormatPercentFormatPercent Returns an expression formatted as a percentage (multiplied by 100) with atrailing % character.Simple Form
FormatPercent (Expression)General Form
FormatPercent (Expression[,NumDigitsAfterDecimal [,IncludeLeadingDigit[,UseParensForNegativeNumbers [,GroupDigits]]]])
For the examples below, assume dblTestNumber contains the value 12345.678
Expression ResultFormatNumber(dblTestNumber, 2, True, True, True) 12,345.68
FormatCurrency(dblTestNumber, 2, True, True, True) $12,345.68
FormatPrecent(dblTestNumber, 2, True, True, True) 1,234,567.80%
"Try It" Code:
Private Sub cmdTryIt_Click()
Dim dblTestNumber As Double
dblTestNumber = Val(InputBox("Please enter a number:"))
Print "Input: "; Tab(25); dblTestNumberPrint "Using FormatNumber:"; Tab(25); FormatNumber(dblTestNumber, 2, True, True,True)Print "Using FormatCurrency:"; Tab(25); FormatCurrency(dblTestNumber, 2, True, True,True)Print "Using FormatPercent:"; Tab(25); FormatPercent(dblTestNumber, 2, True, True, True)End Sub
Output:
7/30/2019 vb-6ch123-110721032904-phpapp01
23/25
3 Cube Computer InstituteVB 6 Notes
Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh
- 23 -
4. FormatDateTimeFormatDateTime Returns an expression formatted as a date or time.
Syntax:
FormatDateTime(Date[,NamedFormat])
The FormatDateTime function syntax has these parts:
Part Description
Date Required. Date expression to be formatted.
NamedFormat Optional. Numeric value that indicates the date/time format used. If omitted,vbGeneralDate is used.
Settings:
The NamedFormatargument has the following settings:
Constant Value Description
vbGeneralDate 0 Display a date and/or time. If there is a date part, display it as a shortdate. If there is a time part, display it as a long time. If present, bothparts are displayed.
7/30/2019 vb-6ch123-110721032904-phpapp01
24/25
3 Cube Computer InstituteVB 6 Notes
Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh
- 24 -
vbLongDate 1 Display a date using the long date format specified in your computer'sregional settings.
vbShortDate 2 Display a date using the short date format specified in your computer'sregional settings.
vbLongTime 3 Display a time using the time format specified in your computer'sregional settings.
vbShortTime 4 Display a time using the 24-hour format (hh:mm).
"Try It" Code:
Private Sub cmdTryIt_Click()
Print "Using vbGeneralDate:"; Tab(25); FormatDateTime(Now, vbGeneralDate)Print "Using vbLongDate:"; Tab(25); FormatDateTime(Now, vbLongDate)Print "Using vbShortDate:"; Tab(25); FormatDateTime(Now, vbShortDate)Print "Using vbLongTime:"; Tab(25); FormatDateTime(Now, vbLongTime)Print "Using vbShortTime:"; Tab(25); FormatDateTime(Now, vbShortTime)End Sub
Output:
7/30/2019 vb-6ch123-110721032904-phpapp01
25/25
3 Cube Computer InstituteVB 6 Notes
R f MSDN d P i i VB 6 b J li C B dl & A it C Mill h
Recommended