Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 69

Operators and Expressions

Lesson 9

<<Previous Lesson

<<Table Of Contents>>

Next Lesson>>

You'll learn about some basic operators and the meaning of an expression. The
operators discussed here are the basic ones, more operators are provided by
the Visual Basic 6 language but they are out of this lesson's scope. I will explain
them later.
Table: Operators and their meanings

Operators Meanings

Operators

Meanings

Addition

>=

Greater than or equal to

Subtraction

<>

Not equal to

Multiplication

equal to

Division

&

String Concatenation

Integer Division

And

Logical And

Mod

Modulo Division

Not

Logical Not

<

Less than

Or

Logical Or

>

Greater than

Xor

Logical Xor

<=

Less than or equal to ^

Power

Assigning values to variables : '='


operator
The Assignment operator (=) is used to assign a value or an expression to
a variable. When you assign a value, its not the same as the Equal to operation,
but the value is copied to a variable. Besides assigning values and expressions,
you can assign a variable to a variable also
Example:
x=a+b
'=' , '+' are the operators.

x,a,b are the operands and 'a+b' is an expression. x=a+b is a statement.


The following program will print 20.
Private Sub cmdDisplay_Click()
Dim num As Integer, r As Integer, n As Integer
n = 10
r=n^2
'n to the power 2
num = n + r / n
Print num
End Sub
Output: 20

The Integer Division Operator ('\')


The Integer Division operator('\') eliminates the decimal part after division.
Example:
Private Sub cmdDivision_Click()
Dim a As Double, b As Double, c As Double
a = 12: b = 5
c=a\b
Print c
End Sub
Output: 2

The 'Mod' operator


The Mod operator is used to calculate remainder.
Example:
Private Sub cmdShow_Click()
Dim remainder As Integer, num As Integer
num = 21
remainder = num Mod 10
Print remainder
End Sub
Output: 1

Boolean Operators : And, Or, Not, Xor


To learn about Boolean operators, you first need to have the concept of If-Else
condition. So Boolean operators are explained in Lesson 18.

Related topics:

Variables and data types


Scope of a variable
If-blocks
Nested if-else

Common Properties in VB6


Lesson 12

<<Previous Lesson

<<Table Of Contents>>

Next Lesson>>

In this lesson, you'll learn about the common properties used in VB6.

BackColor and ForeColor


The BackColor property sets the background color of an object while the
ForeColor property changes the foreground color used to display text.
You can set these properties either from Properties Window or you may wish to
set in run-time.
Example:
When you click on command1 button, the code in the Click event procedure is
executed.
Private Sub cmdChangeColor_Click()
Label1.BackColor = vbRed
Label1.ForeColor = vbBlue
End Sub
On execution, the background color of the label will be red and label's text color
will be blue.
'vbRed' and 'vbBlue' are the color constants.
Another example:
Private Sub cmdChangeColor_Click()
Label1.BackColor = vbRed
Label1.ForeColor = vbBlue
Form1.BackColor = vbGreen
Text1.BackColor = vbBlack
Text1.ForeColor = vbYellow
Frame1.BackColor = vbWhite
End Sub
The color can also be expressed in hexadecimal code.
Example:

Private Sub cmdChangeColor_Click()


Label1.BackColor = &HFF&
Label1.ForeColor = &HC00000
End Sub
In this case, you have to copy the hexadecimal code from Properties Window.

Font
You can set the font property from the Properties Window. See the below
example to set property in run time.
Example:
Private Sub cmdChangeFont_Click()
Text1.FontSize = 16
Text1.FontBold = True
Text1.FontItalic = True
Text1.Font = "Tahoma"
End Sub
The above block of code can be written in the following way too.
Private Sub cmdChangeFont_Click()
Text1.Font.Size = 16
Text1.Font.Bold = True
Text1.Font.Italic = True
Text1.Font.Name = "Tahoma"
End Sub

Caption
It sets the text displayed in the object's title bar or on the object.
Example:
Private Sub cmdSetTitle_Click()
Form1.Caption = "New Program"
Label1.Caption = "Hello"
Frame1.Caption = "New frame"
End Sub

'Caption' property of form sets the form's title text. The text to be displayed on
label is set.

Text
It sets the text in a TextBox.
Example:
Text1.Text = "New program"

Here the text string is assigned to Text1.Text.

Download sample program: Set Properties

The above program is explained in the following page:

Easy VB6 samples

The Left, Top, Width and Height


properties
1. The Left Property sets the distance between the internal left edge of an
object and the left edge of its container.
2. The Top Property sets the distance between the internal top edge of an
object and the top edge of its container.
3. The Width Property sets the width of an object.
4. The Height Property sets the height of an object.
Example:
Private Sub cmdChange_Click()
Form1.Left = 12000
Form1.Top = 7000
Form1.Height = 10000
Form1.Width = 12000
End Sub

Container
Moves an object into another container. You don't see it in the Properties
Window, it is a run-time only property.
In this case, you need to start with the 'Set' keyword.
Example:
Set Command1.Container = Frame1
The command1 control will be moved into frame1.

Visible
Determines whether an object is visible or hidden.
Example:
Label1.Visible = False

Enabled
Determines whether an object can respond to user generated events.
Example:
Text1.enabled=False

MousePointer and MouseIcon


The MousePointer property sets the type of mouse pointer over an object. The
values of MousePointer property are
0- Default
1- Arrow
2- Cross
3- I-Beam
4- Icon
5- Size etc.
The MouseIcon property sets a custom mouse icon from your files.

Download sample program: Form Design

The above program is explained in the following page:

Some simple VB6 examples

TabIndex and TabStop


The TabStop property indicates whether the user can use the TAB key to give
the focus to an object. You can give focus to the objects pressing the TAB key in
the daily use software applications.
The TabIndex property sets the tab order of an object.
Example:
Command3.TabIndex = 0
Command2.TabIndex = 1
Command1.TabIndex = 2
When you press the TAB key, the focus will be given on Command3 first, then
on Command2 and at last on Command1.

Movable
Determines whether an object is movable.

Locked
Determines whether an object e.g TextBox can be edited.

Tag
Stores any extra data for your program that is used in the code.

Control Box

Indicates whether a control-menu box is displayed on the form at run time. If


this property is set to False, the Close Button, Minimize Button and Maximize
Button are not shown on the form.

ShowInTaskBar
Determines whether the form appears in the windows taskbar.

StartUpPosition
Specifies the position of the form when it first appears.

Icon
Sets the icon displayed when the form is minimized at run time.

Related topics:

The CommandButton control


Label & TextBox
CheckBox
Timer
Scroll bars
Image and PictureBox
OptionButton & Frame
The ListBox control
The ComboBox control
DriveListBox, DirListBox & FileListBox

Input and Output Operations in VB6


Lesson 15

<<Previous Lesson

<<Table Of Contents>>

Next Lesson>>

Visual Basic provides some excellent ways for input and output operations.
Input can be taken using TextBox, InputBox, and output can be shown with the
Print method, TextBox, Label, PictureBox and MsgBox.

Input and output using TextBox


The TextBox Control provides an efficient way for both input and operations.
The following sample program shows it.
Example:
Private Sub Command1_Click()
Dim a As Integer
a = Val(Text1.Text)
a=a+1
Text2.Text = a
End Sub
In the above program, Input is taken using Text1 and output is shown in Text2,
where output is the incremented value of the input.

Download sample program: Sum Calculator

The Sum Calculator program is explained here: Some simple VB6 examples.

InputBox
InputBox is a function that prompts for user-input. InputBox shows a dialog box
that inputs value from the user.
Syntax:
a=InputBox( promt, [Title], [Default], [xpos], [ypos])
where 'a' is a variable to which the value will be assigned. The texts inside the

InputBox are optional except the "prompt" text. "prompt" text is the prompt
message. "title" is the title of the message box window. "Default" is the default
value given by the programmer. 'xpos' and 'ypos' are the geometric positions
with respect to x and y axis respectively.
Note: Parameters in brackets are always optional. Do not write the brackets in
your program.
Example:
Private Sub cmdTakeInput_Click()
Dim n As Integer
n = InputBox("Enter the value of n : ")
Print n
End Sub
The above program prints the value of n taken from the InputBox function.
Example: InputBox with the title text and default value.
Private Sub cmdTakeInput_Click()
Dim n As Integer
n = InputBox("Enter the value of n : ", "Input", 5)
Print n
End Sub
The InputBox dialog appears with the title "Input" and the highlighted default
value in the provided text field is 5.

MsgBox
The MsgBox function shows a dialog box displaying the output value or a
message.
Syntax:

MsgBox Prompt, [MsgBox style], [Title]

where Promt text is the prompt message, [MsgBox Style] is the msgbox style
constants and [Title] is the text displayed in the title bar of the MsgBox dialog.
Example:
Private Sub cmdShowMessage_Click()
Dim n As Integer
n = 10

MsgBox "The value of n is " & n


End Sub

Example: MsgBox with the dialog type and title text.


Private Sub cmdShowMessage_Click()
Dim n As Integer
n = 10
MsgBox "The value of n is ", vbInformation, "Result" & n
End Sub
The MsgBox dialog box appears with the 'vbInformation' dialog type and the
title text is '"Result".
The list of dialog types is shown in the Quick Info text upon entering the Prompt
text.
Download the following programs:

InputBox & MsgBox 1

InputBox & MsgBox2

The above programs are explained here: VB6 source code for beginners.
Example: The following program shows how the MsgBox function returns value.
Private Sub Command1_Click()
n = MsgBox("hello", vbOKCancel)
If n = 1 Then
Print "You have pressed ok"
ElseIf n = 2 Then
Print "You have pressed cancel"
End If
End Sub
When you click the button, the MsgBox dialog appears. Then the user either
presses Ok or Cancel in this case. The MsgBox function returns 1 if you press
Ok, it returns 2 if you press Cancel.

Line continuation character( _)

In your vb program you can type maximum of 1023 characters in a line. And
sometimes, it doesn't fit in the window when we write so many characters in a
line. So Line Continuation Character (underscore preceded by a space) is used
to continue the same statement in the next line.
Example:
Private Sub cmdShow_Click()
MsgBox "Hello, welcome to www.vbtutes.com", _
vbInformation, "Welcome"
End Sub

Output using PictureBox


PictureBox is also used for the output operation. The output is displayed using
the Print method.
Example:
Private Sub cmdDisplay_Click()
Dim n As Integer
n = 40
picResult.Print n + 5
End Sub
The program prints 45 in the PictureBox.

Download sample program: Output with PictureBox

Get this program explained here.

Input-output with File


Input-output operations are also possible using File in Visual Basic discussed in
the appropriate lessons. In this case, the input is taken from the data saved in
Windows Notepad , in .txt extension and output can be displayed in the same
file.

Output to the printer

The output can be displayed using printer . Visual Basic easily lets you display
the output value or the output message using printer. Visual Basic treats the
printer as an object named Printer. This topic is discussed in the appropriate
lesson.

Related topics:

The TextBox control


The PictureBox control

OptionButton and Frame Controls


Lesson 22

<<Previous Lesson

<<Table Of Contents>>

Next Lesson>>

Have a look at some interesting features of the OptionButton and


Frame controls in Visual Basic 6. I'm discussing the frame control with option
button in this lesson, because the Frame control is often used with option
buttons when you want to have a couple of groups of the option button
controls.
Note that in the higher versions of Visual Basic and in some other languages,
the term Radio Button is used instead of Option Button for the same control.

The OptionButton Control


This control lets you choose from several items among other in a list. This is
one of the mostly frequently used controls in application developement. When
you click on an OptionButton, it is switched to selected state or ON state, and
all other option buttons in the group become unselected or OFF.
Example:
Private Sub Command1_Click()
If Option1.Value = True Then
Print "Option1 is ON"
Else
Print "Option1 is OFF"
End If
End Sub
Output:

When Option1.value = True then the Option Button is ON and when


Option1.value = False then the Option button is OFF.

Example:
Private Sub cmdCheck_Click()
If optWindows.Value = True Then
Print "Windows is selected"
ElseIf optLinux.Value = True Then
Print "Linux is selected"
ElseIf optMac.Value = True Then
Print "Mac is selected"
End If
End Sub
Output:

Download sample program: Option Button Example

See the following page for the above program's code and exaplanation:

Eight essential VB6 programs.

Frame

Frame is a container control as the Frame control is used as a container of other


controls. The controls that are on the frame or contained in the frame are said
to be the child controls. Use the Caption property to set the frame's title.
One of the most useful features of the Frame control is that when you move the
frame, all the child controls also go with it. If you make the frame disabled or
invisible, all the child controls also become disabled or invisible.
This container control is often used when you wish to select more than one
OptionButton controls which are separated in a couple of groups like in the
following sample program.

Download sample program: Format Text

Get the above program explained here: Samples.

Related topics:

The CheckBox control


Image and PictureBox
Graphical style of OptionButton and CheckBox

The CheckBox Control


Lesson 23
<<Previous Lesson

<<Table Of Contents>>

Next Lesson>>

In this lesson, I'll give you an overview of the CheckBox control in VB6. This is
obviously a powerful tool in the Visual Basic 6 IDE.
Unlike the OptionButton control, the CheckBox control lets you perform multiple
selections, meaning that the end user of your finished software product will be
able to have multiple choices from a list of items.
This control has three states : checked, unchecked and grayed. The value
property determines the checkbox state.
Example:
Private Sub cmdShow_Click()
If Check1.Value = 1 Then
Print "Checked !"
ElseIf Check1.Value = 0 Then
Print "Unchecked !"
End If
End Sub
Output:

If you assign Check1.Value =1 then the CheckBox is checked and if


Check1.Value = 0 then it is unchecked. If Check1.Value = 2 then the checkbox
is grayed.

Example: The previous program can also be written in the following way.

Private Sub cmdShow_Click()


If Check1.Value = vbChecked Then
Print "Checked !"
ElseIf Check1.Value = vbUnchecked Then
Print "Unchecked !"
End If
End Sub
Output:

'vbChecked' and 'vbUnchecked' are vb constants whose values are 1 and 0


respectively.
The grayed state can be set using the 'vbGrayed' vb constant whose value is 2.

Example: Program to make multiple choices.


Private Sub cmdShow_Click()
If chkTea.Value = 1 Then
Print "Tea"
End If
If chkCoffee.Value = 1 Then
Print "Coffee"
End If
If chkPizza.Value = 1 Then
Print "Pizza"
End If
If chkChocolate.Value = 1 Then
Print "Chocolate"
End If
End Sub
Output:

I've wrtiten a small program to demonstrate how to use the


option button controls in your project.

Download sample program: Restaurant Order 1

Go to the following link for code and explanation of the above program sample:

Eight essential VB6 programs

Apart from checked and unchecked states, there is another state called grayed
state. The grayed state is used to indicate that the checBox is unavailable.
Grayed state:

The grayed state can be set using the value property from the Properties
Window or you may want to set this property in run-time.
Example:
Check1.Value = vbGrayed
Or,
Check1.Value = 2

Related Topics:

OptionButton & Frame


Graphical style of OptionButton and CheckBox controls

PictureBox and Image Controls


Lesson 25

<<Previous Lesson

<<Table Of Contents>>

Next Lesson>>

Today I'll show you the usage of PictureBox and Image controls. They are used
to display images, you guessed it? But there are some differences between the
two controls. There are certain cases when the Image control is suitable, and in
some other, the PictureBox control will make your task easier, though both of
them share the same job. So lets dig into some details!

Where to use images?


The first plain fact to know is that the Image and PictureBox controls are used
to display pictures or icons on the form. You develop a software and you don't
use any picture, that does not make sense. You generally use pictures or icons
for the company logo and to make your software more graphical that'll surely
make your application user-friendly. You can make use of the images on the
splash screen and in many other cases.

Supported Picture Formats


The supported picture formats for these control include BMP, DIB (bitmap), ICO
(icon), CUR (cursor), WMF (metafile), EMF (enhanced metafile), GIF and JPEG.
You can't use a PNG format.
Firstly I'll talk about the PictureBox control and then the Image control. Lastly
the comparison and differentiation between them will be discussed along with
the explanation of when to use one or another.

The PictureBox control


The following points describe a PictureBox control:

The pictureBox control comes with a light border around it.

Works as a container: You can place any other control on it, when you
move the PictureBox control, all the controls on it moves along with. That
means, it works as a container of other controls.
Similarity with the Form: This control is so similar to a form as both of
them support all the graphical properties, graphical methods and
conversion methods.
Supports all the graphical properties: It supports all the graphical
properties such as AutoRedraw, ClipControls, HasDC, FontTransparent,
CurrentX, CurrentY, and the Drawxxxx, Fillxxxx, and Scalexxxx
properties.
Supports all the graphical methods: It supports all the graphical
methods such as Cls, PSet, Point, Line, and Circle.
Supports the conversion methods: It supports the conversion
methods such as ScaleX, ScaleY, TextWidth, and TextHeight.
Loading images: Using the Picture property, you can load a picture in
design time and run-time. The LoadPicture function is used to load the
picture from your computer. This function is used with both the
PictureBox and Image controls.

Example:
Picture1.Picture = LoadPicture("D:\\PictureName.jpg")
Example:
Image1.Picture = LoadPicture("D:\\PictureName.jpg")

Clearing the current image: You can clear the current image of the
PictureBox or Image control in design time by clearing the value of Picture
property. This can also be done in run-time in the following way.

Picture1.Picture=LoadPicture("")
or
set Picture1.picture=Nothing
Download this sample: Image Show

The Image Control


The image control has almost the same features of PictureBox.

Loading Images: You load an image in the same way.

Example:
Image1.Picture = LoadPicture("D:\\PictureName.jpg")

The Stretch property: If you set the Stretch property to true, it stretches
the picture to fit in the control.

How the Image control is different


from PictureBox?
1. Image controls are less complex than PictureBox controls.
2. The Image control does not have border around it like a PictureBox
control.
3. The image control does not work as a container.
4. The Image controls do not have graphical properties, graphical methods
or conversion methods such as ScaleX, ScaleY, TextWidth, and
TextHeight.
5. The PictureBox control does not have the Stretch property.
6. The Image control comparatively takes less memory, so it loads faster.

Copying an image from one control to


another
You can assign the Picture property of one control to another.
Example:
Picture2.Picture = Picture1.Picture
Or,
Image2.Picture = Image1.Picture
As a conclusion I want to say that many Visual Basic programmers prefer the
Image control over PictureBox as the Image control consumes less memory
resource resulting a faster loading of it. Besides, it supports all the events a

pictureBox can have, and you can even have a border around it from the
BorderStyle property.
The only big limitation is that it cannot work as a container. For this reason, the
PictureBox control can be sometimes preferred much. But above all, you should
always choose one which is appropriate for your application.
Related topic:

Input/output operations

Form Events
Lesson 29

<<Previous Lesson

<<Table Of Contents>>

Next Lesson>>

This lesson is about the form events in Visual Basic 6. Learn about the other
events in Lesson 26: Common events.
Before the form becomes fully functional, a series of form events is invoked one
by one when you run your program. They are discussed here according to this
order.

Initialize
The Initialize event is the first event of a form when the program runs. This
event is raised even before the actual form window is created. You can use this
event to initialize form's properties.
Example:
Private Sub Form_Initialize()
Text1.Text = ""
Text2.Text = ""
End Sub

Load
After the Initialize event, Load event fires when the Form is loaded in the
memory. This Form event is invoked for assigning values to a control's property
and for initializing variables.
Note that the form is not visible yet. For this reason, you cannot invoke a
graphic function like Cls, PSet, Point, Circle, Line etc and you cannot give the
focus to any control with the SetFocus method in the form's Load event
procedure. The Print command will not even work.
On the other hand, this won't be a problem setting a control's property in the
form's load event.
Example:

Private Sub Form_Load()


Text1.Text = ""
Text2.Text = ""
var1 = 0
End Sub

Resize
After the Load event, the form receives the Resize event. The form's Resize
event is also raised when you resize the form either manually or
programmatically.

Activate and Deactivate


After the Resize event, Activate event fires. While working with multiple forms,
the Activate event fires when the form becomes an active form in the current
application, and the Deactivate event fires when the other form becomes the
active Form.
Another important form event is the Paint event which I'll not discuss here.
Paint event will be covered later in another lesson.
Note that when you run your program, form events such as Initialize, Load,
Resize, Activate and Paint events are raised automatically one by one. The Paint
event is not raised when the form's AutoRedraw property is set to True.

QueryUnload
When you close or unload the form, the form first receives the QueryUnload
event and then the Unload event.
The QueryUnload event is invoked when the form is about to be closed. When
the form is closed, it may be unloaded by the user, the task manager, the code,
owner form, MDI form or it may be closed when the current windows session is
ending.
Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode _
As Integer)

'code here
End Sub
This event procedure takes two parameters, Cancel and UnloadMode. The
Cancel parameter cancels the unload operation, and depending on the symbolic
values of UnloadMode, a particular task can be performed.
Example:
Private Sub Form_QueryUnload(Cancel _
As Integer, UnloadMode As Integer)
If UnloadMode = vbFormControlMenu Then 'vbFormControlMenu=0
MsgBox "the form is being closed by the user."
End If
End Sub
The other constants are vbFormCode, vbAppWindows, vbAppTaskManager,
vbFormMDIForm, vbFormOwner.
Symbolic constant values for the UnloadMode parameter are explained below:

vbFormControlMenu: when the form is closed by the user.


vbFormCode: Use this constant when you're closing a form by code.
vbAppWindows: when the current windows session is ending.
vbAppTaskManager: when the task manager is closing the application.
vbFormMDIForm: when the MDI parent is closing the form.
vbFormOwner: when the owner form is closing.

Unload
The Unload event fires when the Form unloads. You can use this event to warn
the user that data needs to be saved before closing the application.
Example: In this program, you cannot close the Form keeping the text field
blank
Private Sub Form_Unload(Cancel As Integer)
If Text1.Text = "" Then
MsgBox "You cannot exit keeping the text field blank"
Cancel = True
End If
End Sub

When Cancel = True, you cannot close the Form. The Cancel parameter is used
to cancel the the form's unload operation.
In the next lesson, you'll learn about the mouse hover effect.
Related topics:

Common events
Concept of event-driven programming
Mouse hover

Line and Shape


Lesson 31

<<Previous Lesson

<<Table Of Contents>>

Next Lesson>>

Line and shape are the simplest controls in Visual Basic 6 IDE that do not raise
events. They are only used for designing the program interface. You can
enhance the graphical user interface (GUI) of your application using
these two controls. The knowledge of using them appropriately will greatly
improve your software. You can easily learn about the properties of Lines and
shape. Just experiment !!!

The Line control


Line is used to draw lines.
Some properties of the Line control are explained below:

BorderColor: The BorderColor property sets the Line color.


BorderStyle: The BorderStyle property sets the style of the line like solid,
dash, dot and other styles.
BorderWidth: The BorderWidth property sets the line width.
DrawMode: The DrawMode property has several symbolic constant values
or named constant values that determine the appearance of the line
control.

The Line method


You can even draw a line from your code. The Line method does the job.
Line (x1, y1)-(x2, y2), color
Example: This example draws a line of 5 twips width.
DrawWidth = 5
Line (0, 0)-(500, 600), vbRed
You need to type the minus ("-") sign between the two points.

Shape
Shape is used to draw different kinds of shapes. The shapes that you can draw
using this control are rectangle, square, oval, circle, rounded rectangle and
rounded square.
Shape control also has the same properties as the Line control plus some other
simple properties such as BackColor that sets the background color, FillStyle
that sets the filling style of the shape and FillColor that sets the color filling the
shape.
Different shapes can be drawn from the code using some methods which are
out of the scope of this lesson. They will be discussed later.
Download sample program: I-Card
Related topic:

Image & PictureBox

Numeric Functions
Lesson 34

<<Previous Lesson

<<Table Of Contents>>

Next Lesson>>

This lesson takes you through some of the numeric functions in Visual Basic 6.
There are several numeric functions as well as math functions in VB6. The
Visual Basic language gives you enough power to work with numbers. You can
solve many complex problems related to numeric calculations using the numeric
functions provided by VB6.
I'm going to explain Sqr, Int and Round functions in this section.
Read the following lesson to learn about more numeric functions:

Working with numbers

The Sqr function


The Sqr function returns the square root of a number. This function takes a
Double type argument and returns a Double implying that you can work with
large numbers using the Sqr function.
Example:
Print Sqr(9)
Output: 3

The Int function


The Int function returns the greatest integer less than or equal to the number.
It discards the decimal part of a number. This function greatly helps in
truncating the decimal part of a number. But be aware that in case of a
negative decimal number, it returns a rounded up value, resulting in an
increment of integer part as it's shown in example 3 below.
Example1:
Print Int(2.9)
Output: 2

Example 2:
Print Int(5)
Output: 5
Example 3:
Print Int(-5.8)
Output: -6

The Round function


The Round function rounds a numeric value.
Syntax:
Round(Number, [no. of digits after decimal]
If the second parameter is omitted, the number is rounded to a whole number.
Example:
Print Round(5.8)
Output: 6
Example:
Print Round(5.8, 1)
Output: 5
Example:
Print Round(5.4568, 2)
Output: 5.46
In this lesson, I've not covered all the numeric functions. The other numeric
functions are explained in Lesson 47 : Working with numbers.
Related topics:

Working with numbers

Variables and data types


Formatting functions
Data inspection functions

String Functions
Lesson 37

<<Previous Lesson

<<Table Of Contents>>

Next Lesson>>

There are many useful string functions in Visual Basic 6. The string functions
are defined in the "Strings" module. Search in the object browser.
The string functions are explained below:

Left
The Left function extracts characters from the left of the string.
Syntax:
Left(string, n)
n is the number of characters to be extracted.
Example:
Print Left("Visual", 3)
Output: Vis

Right
The Right function extracts characters from the right of the string.
Syntax:
Right(string, n)
string is the character string, n is the number of characters to be extracted.
Example:
Print Right("Visual", 3)
Output: ual

Mid
Use the the Mid function to extract characters from the middle of the string.

Syntax:
Mid(string, m, n)
string is the character string, the extracted string will begin at mth character, n
is the number of characters to be extracted.
Example:
Print Mid("Visual", 3, 2)
Output: su

Len
The Len function calculates the number of characters in a string.
Example:
Private Sub cmdCount_Click()
Dim str As String
str = "Visual Basic"
Print Len(str)
End Sub
Output: 12

InStr
The InStr function returns the position of first occurrence of a sub-string
contained in a string.
Syntax:
Instr(str1, str2)
Example:
Dim str As String
str = "Visual Basic"
Print InStr(str, "Basic")
Output: 8

Chr & Asc

The Chr function converts an ASCII value to character and Asc function
converts the character to ASCII.
Syntax:
Chr(ASCII value)
Asc(chr)
Example:
Print Chr(65)
Output: A
Example:
Print Asc("A")
Output: 65
Chr(9) and chr(13) are the Tab and Carriage-return characters respectively.
Example:
Print "Hello" & Chr(9) & "world"
Output: Hello

world

Print "Hello" & Chr(13) & "world"


Output:
Hello
world

Str
The Str function returns the string representation of a number.
Syntax:
Str(n)
Example:
Print str(5) + str(7)
Output: 57

LCase & UCase


The LCase function converts an upper case string to lower case and the UCase
converts a lower case string to upper case.
Example:
Private Sub cmdChangeCase_Click()
Dim s As String
s = "HELLO"
Print LCase(s)
End Sub
Output: hello
Example:
Dim s As String
s = "hello"
Print UCase(s)
Output: HELLO

Trim
The Trim function returns a string without leading and trailing spaces.
Example:
Dim s As String
s="
Print Trim(s)

HELLO"

Output: HELLO

LTrim & RTrim


The Ltrim function trims leading spaces and the RTrim function trims trailing
spaces from a string.

StrReverse

The StrReverse function reverses a string.


Example:
Print StrReverse("Basic")
Output: cisaB

Space
Space function returns a specific number of spaces.
Example:
Print Space(10) + StrReverse("Basic")
Output:
Basic
10 spaces before Basic

StrConv
The StrConv function converts the string into a particular case, e.g upper case,
lower case and proper case.
Example:
Print StrConv("hello", vbUpperCase)
Output: HELLO
Print StrConv("hello", vbProperCase)
Output: Hello

StrComp
The StrComp function compares two strings to check whether they match or
not. It returns 0, if the two strings match with one another.

str = StrComp("vb", "vb", vbTextCompare) 'Returns 0


str = StrComp("vb", "VB", vbTextCompare) 'Returns 0
str = StrComp("vb", "VB", vbBinaryCompare) 'Returns 1
If the optional argument is vbTextCompare then this is a case insensitive
comparison, if vbBinaryCompare then it's a case sensitive comparison.

Tab
The Tab(n) function lets the string be displayed at nth position.
Example:
Print Tab(20) ; "Language"
Output:

Language

Download sample program: String Analyzer

Replace
The Replace function finds a sub-string in a string and replaces the sub-string
with another.
Example:
newvalue = Replace("months", "s", "1") 'Returns month1

Related topics:

String concatenation
Formatting functions
Date-time functions

Date-Time Functions
Lesson 49

<<Previous Lesson

<<Table Of Contents>>

Next Lesson>>

There are many useful functions for the date-time operations in VB6. Visual
Basic gives you enough power for handling the date and time. Here youll learn
about those functions in brief.
This post will include the functions that are defined in the DateTime module of
the VBA library. Search DateTime in Object Browser.

Weekday
The weekday function returns the day of the week. It returns
a number representing the day.
Syntax: Variable = weekday(Date, [FirstDayOfWeek])
This function takes two arguments, one is the optional. You need to pass a date
string to this function, and the first day of week which is optional is set to
vbSunday by default.
The constant values of FirstDayOfWeek paramenter are as follows:
vbSunday
vbMonday
vbTuesday
vbWednesday
vbThursday
vbFriday
vbSaturday
vbUseSystemDayOfWeek
Example:
Print Weekday("1/4/2014")
Output: 7

Year

The year function returns the year from the date.


Example:
Print Year("1/4/2014")
Output: 2014

Month
The month function returns the month of the year.
Example:
Dim m As Integer
m = Month("27 / 3 / 2013")
MsgBox m
Output: 3

DateValue
The DateValue function returns the date part from a date/time value.
Example:
Dim dt As Date
dt = DateValue(Now)
Print dt
Output: 1/4/2014

TimeValue
Returns the time part from a date/time value.
Example:

Dim dt As Date
dt = TimeValue(Now)
Print dt
Output: 12:51:25 PM

Day
Returns the day part from a date
Example:
Dt = Day(Now)

Hour
Returns the hour of the day.
Example:
Print Hour(Now)

Minute
Returns the minute of the hour.
Example:
Print Minute(Now)

Second

Returns the second of the minute.


Example:
Print Second(Now)

DatePart
Returns a specific part from a date.
Syntax: DatePart(Interval, Date, [FirstDayOfWeek], [FirstWeekOfYear])
The interval parameter is the interval part of a date you want.
Pass a date value through the Date parameter.
FirstDayOfWeek and FirstWeekOfYear are optional parameters, the values of
which are vbSunday and vbFirstJan1
Example:
Print "year = " & DatePart("yyyy", "4/1/2014")
Print "month = " & DatePart("m", Now)
Print "day = " & DatePart("d", Now)
Print "week = " & DatePart("ww", Now)
Print "hour = " & DatePart("h", Now)
Print "minute = " & DatePart("n", Now)
Print "second = " & DatePart("s", Now)
Print "weekday = " & DatePart("y", Now)
The interval values can be:
yyyy-Year,
m- Month,
d-Day,
ww-Week,
h-Hour,
n-Minute,
s-Second,
y-weekday.

DateSerial

Returns a Date for a specific year, month and day.


Example:
Print DateSerial(2014, 1, 4)

TimeSerial
Returns a time for a specific hour, minute and second.
Example:
Print TimeSerial(13, 15, 55)

DateDiff
Returns the number of time intervals between two dates.
Example:
dt = DateDiff("d", "5 / 5 / 1990", "26 / 4 / 2013")
The first argument is the interval which can have the value among the interval
constants mentioned above.
Related topics:

Working with date and time


Formatting functions
Using the data types - Part 1
Using the data types - Part 2

ListBox Control
Lesson 40

<<Previous Lesson

<<Table Of Contents>>

Next Lesson>>

This lesson shows you how to work with the ListBox control in Visual Basic 6.
The first thing that you may want to do with the ListBox control is to add
items or elements to it. You have two options for that. You can either add items
in design-time or in run-time.

Adding items in design time


You can add items to ListBox using the List property.

Adding items in run-time

You can add items to ListBox using the AddItem method.


Example:
Private Sub Form_Load()
List1.AddItem "England"
End Sub
Here List1 is the ListBox name.
Output:

Deleting an item from ListBox


You can remove an item using the RemoveItem method.
Syntax:
ListBox.RemoveItem n
n is the index of an item. The Index starts from 0, so the index of the second
item is 1.
Example: This program will delete the 1st item from ListBox.
Private Sub Form_Load()
List1.RemoveItem 0
End Sub

Deleting all items


The Clear method removes all items from the Listbox.
Example:
Private Sub Form_Load()
List1.Clear
End Sub

Number of items in the ListBox


The ListCount property counts items in a ListBox.
Example:
Private Sub Form_Load()
Form1.Show
Print lstCountry.ListCount
End Sub
Output:

Index number of the recently added


item
The NewIndex property gives the index number which is most recently added
using the AddItem method.
Example:
Private Sub Form_Load()
Form1.Show
lstCountry.AddItem "England"
lstCountry.AddItem "USA"
lstCountry.AddItem "Germany"
Print lstCountry.NewIndex
End Sub
Output: 2

Index number of the currently


highlighted item
Index number of the currently highlighted item can be obtained using the
ListIndex property. The value of ListIndex is -1 if no item is highlighted.
Example:
Private Sub cmdShow_Click()
Print lstCountry.ListIndex
End Sub
___________________________________________________________
Private Sub Form_Load()
lstCountry.AddItem "England"
lstCountry.AddItem "USA"
lstCountry.AddItem "Germany"
End Sub
Output:

The List property


The particular item of the ListBox having index n can be obtained using the
List(n) property.
Example:
Private Sub Form_Load()
Form1.Show
lstCountry.AddItem "England"
lstCountry.AddItem "USA"

lstCountry.AddItem "Germany"
Print lstCountry.List(0)
End Sub
Output: England

Currently highlighted item


The text property of ListBox gives the currently highlighted item/string.
Example:
Private Sub Command1_Click()
Print lstCountry.Text
End Sub
_______________________________________________________________
Private Sub Form_Load()
lstCountry.AddItem "England"
lstCountry.AddItem "USA"
lstCountry.AddItem "Germany"
End Sub
Output:

Related topics:

Multiple selection features of the ListBox control


The ComboBox control
DriveListBox, DirListBox & FileListBox

ComboBox in Visual Basic 6


Lesson 42

<<Previous Lesson

<<Table Of Contents>>

Next Lesson>>

In this lesson, I'll tell you about the ComboBox control in brief.
ComboBox is the combination of a TextBox and a ListBox. The user can type in
the text field to select an item or select an item manually from the list. All the
properties, events and methods of a ComboBox control are as same as the
ListBox control. So the discussion of ListBox control in previous lessons also
applies for ComboBox control.

Styles of ComboBox
There are three styles of ComboBox controls-- Dropdown Combo, Simple
Combo and Dropdown List. You can change/select the style from the Style
property of ComboBox.

Example:

Private Sub cmdSelectBirthYear_Click()


Print "Your year of birth is" & cboBirthYear.Text
End Sub
________________________________________________________________
_
Private Sub Form_Load()
For i = 1980 To 2012
cboBirthYear.AddItem Str(i) 'Str function returns the
'string representation of a number
i = Val(i)
Next i
End Sub

Download sample program: Registration


Related Topics:

The ListBox control


Multiple selection feature of ListBox
Scroll bars
DriveListBox, DirListBox, FileListBox

Scroll Bars in Visual Basic 6


Lesson 43

<<Previous Lesson

<<Table Of Contents>>

Next Lesson>>

In this lesson, you will learn about the scroll bars - Vertical and Horizontal.
You have seen scroll bars in most of the Windows applications. A scroll bar is a
very important element of a software. When you'll work on a software project in
VB6, you'll need these controls if you have to scroll down or scroll up a page.
Two types of scroll bars are there in the Visual Basic environment -- HScrollBar
(Horizontal Scroll Bar) and VScrollbar(Vertical Scroll Bar).

Most useful properties


The main properties of both the scroll bars are Min, Max, SmallChange,
LargeChange and Value.

Vertical scroll bar

Value
The Value property returns the scroll bar position's value. Each position of the
thumb has a value. The Value changes when you click on one of the arrow
buttons or when you move the thumb by dragging it.

Min
The Min property sets/returns the minimum value of a scroll bar position.

Max
The Max property sets/returns the maximum value of a scroll bar position.

SmallChange
The SmallChange property sets/returns the amount of change to Value property
in a scroll bar when the user clicks on a scroll arrow button.

LargeChange
The LargeChange property sets/returns the amount of change to Value property
in a scroll bar when the user clicks on the scroll bar area.
The Change event fires when an arrow button or the scroll bar area is clicked or
after the thumb has been dragged. The Scroll event is raised when the thumb is
being dragged.
Sample: VScrollBar demo
The following sample program will help you easily learn about the scroll bars.
Download sample program: Length Converter

In some cases, you do not need to use scroll bars as many controls in VB6
provide a scroll bar with them. For example, the TextBox control has a scroll bar
with it, and it becomes enabled when you set the Multi-Line property of the
TextBox control to True .

DriveListBox, DirListBox and


FileListBox Controls
Lesson 44

<<Previous Lesson

<<Table Of Contents>>

Next Lesson>>

In this lesson, I'll talk about the file system controls in VB6.
To work with the file system, the DriveListBox, DirListBox and FileListBox are
used together that will access the files stored in the secondary memory of your
computer. The DriveListBox shows all the drives on your computer, the
DirListBox displays all the sub-directories of a given directory, and the
FileListBox shows the files in a particular directory.
Most of the properties, events and methods are same as the ListBox and
ComboBox controls. So the common things have not been explained in this
section.

Selected Items
The Drive, Path and FileName properties return the selected item in the
DriveListBox, DirListBox and FileListBox respectively. The Drive property returns
the selected disk drive from your computer.

Setting the Drive


Example:
Private Sub Form_Load()
Drive1.Drive = "G"
End Sub

Output:

Working with the three list boxes


together
When the user selects a drive, this change should be reflected in DirListBox and
when the user selects a directory, this change should be reflected in the
FileListBox. Write the following code for that.
Example:
Private Sub Dir1_Change()
File1.Path = Dir1.Path
End Sub
______________________________________________________________
Private Sub Drive1_Change()
Dir1.Path = Drive1.Drive
End Sub

Showing the selected file name


To show only the selected file name, write the following code.
Example: This program will show only the name of the selected file.
Private Sub cmdShowFileName_Click()
Print File1.FileName
End Sub
__________________________________________________________
Private Sub Dir1_Change()
File1.Path = Dir1.Path
End Sub

__________________________________________________________
Private Sub Drive1_Change()
Dir1.Path = Drive1.Drive
End Sub
Output: The output will vary from computer to computer.

The Pattern property of FileListBox


The Pattern property sets which files to be shown in the list. The default value is
*.* (all files). You can specify which types of files to be shown. To enter
multiple specifications, use semicolon as a separator. You can set the Pattern in
run-time also.
Example:
File1.Pattern = "*.bmp;*.ico;*.wmf;*.gif;*.jpg"

Showing the complete file path with


file name

Example:
Private Sub cmdShowFileName_Click()
f = File1.Path
If Right(f, 1) <> "\" Then
f = File1.Path + "\"
End If
Print f + File1.FileName
End Sub
________________________________________________________________
Private Sub Drive1_Change()
Dir1.Path = Drive1.Drive
End Sub
________________________________________________________________
Private Sub Dir1_Change()
File1.Path = Dir1.Path
End Sub
Output: The output will vary from computer to computer.

Download sample program: Photo Viewer


Related topics:

ListBox

ComboBox
Multiple Selection feature of ListBox

How to Add a Menu to Your VB6


Program
Lesson 62

<<Previous Lesson

<<Table Of Contents>>

Next Lesson>>

Menus are one of the most important features of a software product. Every
standard software must have menus. You generally see a menu on top of a
software interface. Menus are controls but different from the controls in the
ToolBox and they don't work like the other controls. You can drop a menu
on the form from the Menu Editor Window. Press Ctrl+E to show the Menu
Editor Window or right-click on the form and click Menu Editor. The Menu Editor
Window can also be shown from the Menu Editor icon of the ToolBar.

Building a menu

Building a menu is very simple, you can do it on your own. Simply fill the
Caption and Name field in the Menu Editor Window and click ok to create it.

Click the right-arrow button to create a submenu. Click Next to create the
next menu item, and click ok once you're done editing the menu items.

A simple form with menu:

Properties of the menu items


The important properties of the menu items are Name, Caption, Checked,
Enabled, Shortcut and Visible. As per your programming need, set the
properties either in run-time or in design time. You can create a shortcut key for
a menu item. In some situations you may want to disable a menu item, you can
acquire it through the Enabled property.
The menu control exposes only one event, the Click event.
Example: Make a menu as same as the following image.

Now write the following code.


Private Sub mnuBlue_Click()
Form1.BackColor = vbBlue 'Makes the Form blue
End Sub
______________________________________________________________

Private Sub mnuGreen_Click()


Form1.BackColor = vbGreen 'Makes the form green
End Sub
______________________________________________________________
Private Sub mnuRed_Click()
Form1.BackColor = vbRed 'Makes the form red
End Sub
______________________________________________________________
Private Sub mnuWhite_Click()
Form1.BackColor = vbWhite 'Makes the form white
End Sub
Now run the program and Click on the menu items and see what happens.

The Checked property


Design a form like the output image of the following program. Create a Help
menu and drop a Label control on the form with the caption 'Help'.
Now write the following code.
Private Sub mnuShowHelp_Click()
If mnuShowHelp.Checked = True Then
mnuShowHelp.Checked = False
Label2.Visible = False
ElseIf mnuShowHelp.Checked = False Then
mnuShowHelp.Checked = True
Label2.Visible = True
End If
End Sub
Output:

Related topics:

Popup menu
CheckBox control

Visual Basic 6 Popup Menu


Lesson 63

<<Previous Lesson

<<Table Of Contents>>

Next Lesson>>

Most of the commercial software products have popup menus as they can make
the application more user-friendly and powerful. When you right
click on windows desktop, a popup menu appears. Visual Basic 6.0 provides a
Popup menu method that you can use in your program to show the popup menu
on the form's surface.
To use the Popup menu method, you first need to create a menu. For example,
create a menu with the name "View". See the example given below.

The PopupMenu method


Syntax:
PopupMenu Menu, [Flags], [X], [Y], [DefaultMenu]
Note: Arguments in [ ] brackets are optional.
Now write the following code in the form's MouseDown event to invoke the
popup menu.
Private Sub Form_MouseDown(Button As Integer, Shift As Integer, X As Single,
Y As Single)
If Button = vbRightButton Then
PopupMenu mnuView 'PopupMenu is a method
End If
End Sub

If you need only the popup menu but not the menu bar, set the Visible property
of the menu control to False in design time.
Sample: Colors PopUp
Related topic:

How to add a menu to your VB6 program

MDI Forms in Visual Basic 6


Lesson 66
<<Previous Lesson

<<Table Of Contents>>

Next Lesson>>

Today I'll share my knowledge of MDI forms with you. In the previous lessons
you've learned about forms -their properties, events and methods. The concept
of form is very vast, so many things have been discussed, and many things are
yet to be discussed.

What is an MDI form?


MDI stands for Multiple Document Interface. You have probably seen many MDI
applications. When you want to handle multiple documents simultaneously, MDI
forms are useful.

How to add an MDI form to the


current project?

Project -> Add MDI form. Click Project from the menu bar and click Add MDI
form. Its simple! Remember, a project can have only one MDI form.

Restrictions of the MDI form


1. You can have only one MDI form per project.
2. You can't place most controls on an MDI form. The only controls that can
be placed on the surface of the MDI form are Menus, Timer,
CommonDialog, PictureBox, ToolBar and StatusBar.
These restrictions are there because MDI forms are special type of forms, only
used to handle multiple child forms.

How does the MDI form work?


In your project, there will be only one MDI parent form with one or more MDI
child forms (or simply child forms).

MDI child form: To add a child form, you have to add a regular form,
and set the MDIchild property to True. You can have many child forms.
You can show an MDI child form using the Show method as same as the
regular forms.

AutoShowChildren property of an MDI form: The default value is


True. When its True, the MDI child forms are displayed when they are
loaded. When the value is False, only then you can keep it hidden after
loading, otherwise not.

Restrictions of the MDI child forms:


1.You can't display an MDI child form outside its parent.
2.You can't display a menu bar on the MDI child form.

Now coming to the point, how the MDI form works. There is generally a menu
bar in the parent form. From there the user opens or creates a new document.
In this way, the user accomplishes his/her work in one or multiple documents,
then saves and closes the document(form). You create instances of a single
form in the code using the Set keyword (Remember the object variables).
'Inside the MDIForm module
Private Sub mnuFileNew_Click()
Dim frm As New Form1
frm.Show
End Sub

ActiveForm property: This is the Object type read-only property of the


MDI form. You can apply this property to one of the children which is the
active form. For example, you can close the active form using this
property from the Close menu command of the menu bar.

'In the MDI form


Private Sub mnuFileClose_Click()
If Not (ActiveForm Is Nothing) Then Unload ActiveForm
End Sub

If you cannot understand the above piece of code, don't worry. You'll get it
when you'll learn about Classes and Objects later in this tutorial. For now, just
note that (ActiveForm Is Nothing) represents that there is no active form. The
Not keyword before it negates the value.

Sample program
I've written an MDI demo application to simplify the topic for you.
Download it now! MDI demo
Related topics:

Multiple forms
BAS module

You might also like