Visual Basic
Visual Basic
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
>=
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
<=
Power
Related topics:
<<Previous Lesson
<<Table Of Contents>>
Next Lesson>>
In this lesson, you'll learn about the common properties used in VB6.
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"
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
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
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:
<<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.
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:
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
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.
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
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:
<<Previous Lesson
<<Table Of Contents>>
Next Lesson>>
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:
See the following page for the above program's code and exaplanation:
Frame
Related topics:
<<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:
Example: The previous program can also be written in the following way.
Go to the following link for code and explanation of the above program sample:
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:
<<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!
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
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.
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:
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.
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:
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
<<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 !!!
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:
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:
Example 2:
Print Int(5)
Output: 5
Example 3:
Print Int(-5.8)
Output: -6
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
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
Str
The Str function returns the string representation of a number.
Syntax:
Str(n)
Example:
Print str(5) + str(7)
Output: 57
Trim
The Trim function returns a string without leading and trailing spaces.
Example:
Dim s As String
s="
Print Trim(s)
HELLO"
Output: HELLO
StrReverse
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.
Tab
The Tab(n) function lets the string be displayed at nth position.
Example:
Print Tab(20) ; "Language"
Output:
Language
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
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
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
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:
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.
lstCountry.AddItem "Germany"
Print lstCountry.List(0)
End Sub
Output: England
Related topics:
<<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:
<<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).
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 .
<<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.
Output:
__________________________________________________________
Private Sub Drive1_Change()
Dir1.Path = Drive1.Drive
End Sub
Output: The output will vary from computer to computer.
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.
ListBox
ComboBox
Multiple Selection feature of ListBox
<<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.
Related topics:
Popup menu
CheckBox control
<<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.
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:
<<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.
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.
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.
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
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