0% found this document useful (0 votes)
26 views

Unit1 VB

Uploaded by

Rajashree B
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

Unit1 VB

Uploaded by

Rajashree B
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 131

computer programming

• Programming means a set of instructions to instruct


the computer to carry out certain jobs
• Earliest programming language is called machine
language which uses the binary code(comprises 0 and
1) to communicate with the computer. difficult to
learn.
• After they invented some high-level programming
languages that are much easier.
• Some high-level programming languages are
Java, Javascript, C, C++, C# and Visual Basic.
Programming Languages

VB
Visual Basic ?
• Visual Basic is a third-generation event-driven
programming language first released by Microsoft in
1991.
• It evolved from the earlier DOS version called
BASIC. BASIC means Beginners' All-
purpose Symbolic Instruction Code.
• Visual Basic is a user-friendly programming language
designed for beginners, and it enables anyone to
develop GUI window applications easily.
• Microsoft has released many versions of Visual
Basic, from Visual Basic 1.0 to the version Visual
Basic 6.0.
Visual Basic Applications
• Geometric Progression, Quadratic Equation
Solver, Simultaneous Equation Solver ,Prime Number
Tester, Factors Finder, Quadratic Function Graph
Plotter.
• inventory management system , investments
calculator, point-of-sale system, payroll system,
accounting program and more to help manage your
business and increase productivity.
• Games : slot machine, reversi, tic tac toe .
• multimedia programs : Smart Audio
Player, Multimedia Player
Object-Oriented Concepts (VB2008 vs VB6)
• Visual Basic 2008 is very much similar to
Visual Basic 6 in terms of syntaxes and
program structure, but their underlying
concepts are very different.
• The main difference is that VB2008 is an
object-oriented Programming Language under
the .NET framework.
• Although VB6 may have some OOP
capabilities, Visual Basic 6 is not an object-
oriented programming language because it
does not have inheritance capabilities.
• On the other hand, VB2008 is an Object Oriented
Programming Language, just like other OOP such as
C++ and Java.
• VB6 is known as a procedural or functional
programming language. Some other procedural
programming languages are C, Pascal, and
FORTRAN.
• An object-oriented programming language has few
core features
– Encapsulation
– Inheritance
– Polymorphism
– Class
Difference
• Application Development : Offline (VB)
• Web Development : Online (HTML )
Starting With VB?
• Start -> Programs -> Microsoft Visual Basic 6.0.
Components of VB
Visual Basic IDE is made up of a number of
components
1. Menu Bar & Tool Bar
2. Project Explorer
3. Properties window
4. Form Layout Window
5. Toolbox
6. Form Designer
7. Object Browser
Menu Bar
• This Menu Bar displays the commands that are
required to build an application.
• The main menu items have sub menu items that can
be chosen when needed.
• The toolbars in the menu bar provide quick access to
the commonly used commands and a button in the
toolbar is clicked once to carry out the action
represented by it.
Toolbox
• The Toolbox contains a set
of controls that are used to
place on a Form at design
time.
• Additional controls can be
included in the toolbox by
using the Components
menu item on the Project
menu.
• Pointer : Provides a way to move and resize the controls form
• PictureBox: Displays icons/bitmaps and metafiles. It displays text
or acts as a visual container for other controls.
• TextBox: Used to display message and enter text.
• CommandButton: Used to carry out the specified action when the
user chooses it.
• CheckBox: Multiple selection.
• OptionButton: Option Button control which is a part of an option
group allows the user to select only one option even it displays
multiple choices.
• ListBox: Displays a list of items from which a user can select one.
• ComboBox: Contains a TextBox and a ListBox. This allows the
user to select an item from the dropdown ListBox, or to type in a
selection in the TextBox.
• HScrollBar and VScrollBar: These controls allow the user to
select a value within the specified range of values.
• Shape: Used to add shape (rectangle, square or circle) to a Form.
• Line: Used to draw straight line to the Form
Properties Window
• The Properties Window is docked
under the Project Explorer window.
• The Properties Window exposes the
various characteristics of selected
objects.
• Each and every form in an
application is considered an object.
• Each object in Visual Basic has
characteristics such as color and
size.
• All these characteristics of an object
are called its properties.
• Thus, a form has properties and any
controls placed on it will have
properties too.
• All of these properties are displayed
in the Properties Window.
Form Designer Window
Form Layout Window
• Form Layout window is a simple
visual basic design tool displays
thumbnail view of the current
form.
• This helps in controlling the form
position in the Windows
environment. When more number
of forms are there in a particular
program.
• This “Form Layout” window is
helpful to arrange all the forms
onscreen, in exactly the way in
which the user needs them.
• By simply dragging the miniature
form to a particular location, the
position of a form can be set in
the “Form Layout” window.
Project Explorer
• Docked on the right side of the screen, just under the toolbar, is the Project
Explorer window.
• The Project Explorer serves as a quick reference to the various elements of
a project namely form, classes and modules.

• All of the object that make up the application are packed in a project.
• A simple project will typically contain one form .It is possible to develop
any number of forms for use in a program, although a program may consist
of a single form
Object Browser
• The Object Browser allows us to browse
through the various properties, events and
methods.
• It is accessed by selecting Object Browser
from the View menu or pressing the key F2.
• View→ Object Browser (F2)
IDE
• All these components of the initial VB screen
makes the IDE (Integrated Development
Environment)
• Initially it was SDI (Single Document
Interface) later it was designed as MDI
(multiple Document Interface)
• SDI- One application/window opened
• MDI –Many application/Window opened.
Properties,Methods and Events
• All the controls except pointer are objects in
VB.
• Real-world objects –Properties (Ex: Flower-
color,Shape,fragrance)
• Properties –named attribute of a programming
object and it defines the characteristics of an
object.
• Textbox : enabled/disabled , Font, multiline,
text,visible,width etc..
Methods
• An action that can be performed on objects.
• In OOP, a method that is connected or built-in
procedure to invoke any action on object.
• Ex: text1.setfocus
text1.refresh
Events ?
• An event is a signal that informs an application
that something important has occurred.
• when a user clicks on a form, the form can
raise a Click event and call a procedure that
handles the event.
Event Handlers
• Event handlers are procedures that are called
when a corresponding event occurs.
• We can use any valid subroutine as an event
handler.
Ex :Mouse Events
• Visual Basic responds to various mouse events,
which are recognized by most of the controls.
• The main events are MouseDown,
MouseUp and MouseMove.
• MouseDown occurs when the user presses any
mouse button
• MouseUp occurs when the user releases any
mouse button.
• These events use the arguments button, Shift, X,
Y and they contain information about the mouse's
condition when the button is clicked.
• Textbox
– change Event
– Mouse Move Event
– Click Event
Working With forms
• Form –Basic object.
• Form window- code and objects that creates
user interface.
• Covers Entire screen or many forms contained
in a single screen.
• Default –Form1
• Change the form name using caption property.
• Every form has its own properties,methods and
events.
Methods

• Show
• Load ,unload
• Hide ,unhide
Forms Runtime and design time
properties
Syntax : object .property Name = Value

Ex : form1.caption = “Sample program1:


form1.width = 5000
form1.height = 5000
form1.windowstate = vbNormal
Developing an Application
Visual Basic program consists of 2 Steps
• Visual programming Step (Designing )
• Coding step
Hello World! Program
Coding output

Private Sub Command1_Click()


MsgBox “HELLO!"
End Sub
• Start :
https://www.youtube.com/watch?v=hoXNLd-wvJc
• Display Message box :
https://www.youtube.com/watch?v=cRaui_pDUHM
• ADD :
https://www.youtube.com/watch?v=KTlwfc36cDs
• Login form :
https://www.youtube.com/watch?v=DsSxrxmlkZs&
list=RDCMUCSh0BxhnlW0HJvNI3890JNA&start
_radio=1&t=4
Variables,Datatypes and Modules
• VB uses building blocks such as Variables,
Data types, Procedures, Function and Control
Structures in its programming environment
Modules (3)
➢ Form Modules (one form –one code )
➢ Standard Modules (common code- no repeat)
➢ Class Modules (foundation of OOPs, .CLS
ext,new objects can be created using code)
Class Module
• Declaration-may include constant ,type ,variables and
DLL procedure declarations
• Procedures –A sub function or property procedure that
contains pieces of code that can be executed as a unit.
• Data Types
• Dim [Variable Name] As [Data Type]
Dim [Variable Name] As [Data Type] = [Value]
Data Types
Numeric Datatypes Non-Numeric Datatypes

Byte 1 byte Store integer values in the range of 0 - 255


Store integer values in the range of
Integer 2 bytes
(-32,768) - (+ 32,767)
Store integer values in the range of
Long 4 bytes
(- 2,147,483,468) to (+ 2,147,483,468)
Store floating point value in the range of
Single 4 bytes
(-3.4x10-38) to (+ 3.4x1038)
Store large floating value which exceeding
Double 8 bytes
the single data type value
store monetary values. It supports 4 digits
Currency 8 bytes to the right of decimal point and 15 digits
to the left
Non-numeric data comprises text or string data types, the Date
data types, the Boolean data types that store only two values
(true or false), Object data type and Variant data type.

Type Storage Range

String Length of string 1 to 65,400 characters


January 1, 100 to
Date 8 bytes
December 31, 9999
Boolean 2 bytes True or False

Object 4 bytes Any embedded object

Variant 16 bytes Supports number & string


Non-Numeric Datatypes
1. String : Use to store alphanumeric values. A variable
length string can store approximately 4 billion characters
2. Date : Use to store date and time values. A variable
declared as date type can store both date and time values
and it can store date values 01/01/0100 up to 12/31/9999
3. Boolean : Boolean data types hold either a true or false
value. These are not stored as numeric values and cannot
be used as such. Values are internally stored as 1 (True)
and 0 (False) and any non-zero value is considered as
true.
4. Variant: Stores any type of data and is the default
Visual Basic data type. In Visual Basic if we declare a
variable without any data type by default the data type is
assigned as default.
Variables
• A variable is a location in memory where a
value can be stored during the execution of a
Visual Basic application.
• Visual Basic variables are assigned names by
the programmer when they are declared, so
that they can easily be referenced in other
places
• variables provide a way to reserve memory
locations for the storage of values of various
types
Variable Naming convention
• The first character must always be alphabetic.
• Variable names can be letters and numbers and the
underscore character.
• The name must start with a letter and can have a
maximum of 254 characters
• cannot use spaces or periods.
• some punctuation characters not allowed
( * . , # $ % & !).
• VB has a large number of "reserved words" that
cannot be used for variable names.
Ex :"Sub", "Function", "Array", "Integer", etc.
Variable Declaration
• Declaring Variables : In most programming languages, variables must be declared
in advance. It should be known to the compiler before execution. We can declare
variables in 2 ways.

• Explicit Declaration

• Implicit Declaration

i) Explicit Declarations : To declare a variable, use the Dim statement


followed by the variable’s name .

ii) Syntax : Dim variable [As Type]


Ex : Dim X as Integer

The variables are declared with a Dim statement with variable name and its

type. This is called explicit declaration.


Explicit Declaration
➢ This forces the user to declare all the variables.
➢ The Option Explicit statement checks in the
module for usage of any undeclared variables and
reports an error to the user.
➢ The Option Explicit statement can be explicitly
placed in the general declaration section of each
module using the following steps.
➢Click Options item in the Tools menu
➢Click the Editor tab in the Options dialog box
➢Check Require Variable Declaration option and then
click the OK button
Implicit Declaration
• It is not compulsory that a variable should be declared
before using it.
• Automatically whenever Visual Basic encounters a
new variable, it assigns the default variable type and
value. This is called implicit declaration.
• This type of declaration is easier for the user, to have
more control over the variables, it is advisable to
declare them explicitly.
EX : Dim var1
var1= ”HAI”
Initializing Visual Basic Variables
• Visual Basic variables may be initialized either
during the declaration, or after the declaration.
• It is recommended that variables be initialized
during the declaration.
• Initialization is performed using the Visual
Basic assignment operator (=).
– Ex: Dim X =5
• Any change for value x is needed during
program execution, then it can be done by
reassigning a new value.
Assigning Values to variables
• A variable is assigned value using assignment
operator (=)
• Syntax : variable = <Expression> or Value
• Ex : num=345
• X=Y+Z
• Num, X- Name of the Variable
• 345- value assigned
• Y+ Z - expression
Lifetime & Scope of a variable
• Lifetime : lifetime is how long the variable
retains its value for.
• Scope: The scope refers to where the variable
can be used.
• Procedure level – Private(only inside that
procedure not outside.)
• Module level- Private (Only accessed inside
Module)
• Global Level – Public ( accessible to all)
Local Variables
• A local variable is one that is declared inside a
procedure.
• This variable is only available to the code
inside the procedure and can be declared using
the Dim statements as given below.
• Dim sum As Integer
Static Variables
➢ Static variables are not reinitialized each time
Visual Basic Invokes a procedure and therefore
retains or preserves value even when a procedure
ends.
➢ In case we need to keep track of the number of
times a command button in an application is
clicked, a static counter variable must be
declared.
➢ These static variables are also ideal for making
controls alternately visible or invisible.
➢ A static variable is declared as given below.
Static num As Integer
Module Level Variables
➢ A module level variable is available to all the
procedures in the module.
➢ They are declared using the Public or the Private
keyword.
➢ If you declare a variable using a Private or a Dim
statement in the declaration section of a module- a form
module, a class module, and so on—you're creating a
private module-level variable.
➢ Such variables are visible only from within the module
they belong to and can't be accessed from the outside.
➢ In general, these variables are useful for sharing data
among procedures in the same module
Sub class add

/* coding here*/

End Sub
SCOPE of a Variable
Global Level
Dim X as Integer
(visible to the whole form )

Procedure level
Dim y as integer
(Visible only within Procedure

Module level (like forms)


Dim Z as integer
(visible between procedures using
public/private)
Constants
• Constants are named storage locations in memory.
• The value of which does not change during
program Execution. They remain the same
throughout the program execution.
• When the user wants to use a value that never
changes, a constant can be declared .
• The Const statement is used to create a constant
• Ex : Dim Y As Integer = 10
Const Pi As Single = 3.142
PROCEDURES AND CONTROL
STRUCTURES
➢ Visual Basic offers different types of
procedures to execute small sections of
coding in applications.
➢ Visual Basic programs can be broken into
smaller logical components called Procedures.
➢ Procedures are useful for condensing repeated
operations such as the frequently used
calculations, text and control manipulation
etc.
Functions in VB
• Modular programming
• We use procedures and functions to create
modular programs.
• Visual Basic statements are grouped in a
block enclosed by Sub, Function and
matching End statements.
• The difference between the two is that
functions return values, procedures do not.
Procedures
• A procedure and function is a piece of code in
a larger program. They perform a specific task.
• The advantages of using procedures and
functions are:
– Reducing duplication of code
– Decomposing complex problems into simpler
pieces
– Improving clarity of the code
– Reuse of code
– Information hiding
procedures
➢ It is easier to debug a program a program with
procedures, which breaks a program into
discrete logical limits.
➢ Procedures used in one program can act as
building blocks for other programs with slight
modifications.
➢ A Procedure can be Sub, Function or Property
Procedure.
Procedures
• Sub procedures
• Event procedure
• General procedures
• Function procedures
• Property procedures
Sub Procedures
• A sub procedure can be placed in standard, class
and form modules. Each time the procedure is
called, the statements between Sub and End Sub are
executed. The syntax for a sub procedure is as
follows:

[Private | Public] [Static] Sub Procedure name


[( arglist)]
[ statements]
End Sub
Syntax and its types
General Procedures
➢ A general procedure is declared when several
event procedures perform the same actions.
➢ It is a good programming practice to write
common statements in a separate procedure
(general procedure) and then call them in the
event procedure.
• In order to add General procedure, The Code
window is opened for the module to which the
procedure is to be added.
Event Procedures
• An event procedure is a procedure block that
contains the control's actual name, an underscore(_),
and the event name.
• The following syntax represents the event
procedure for a Form_Load event.

Private Sub Form_Load()


....statement block..
End Sub

• Event Procedures acquire the declarations as Private


by default.
Function Procedures
➢ Functions are like sub procedures, except they
return a value to the calling procedure.
➢ They are especially useful for taking one or more
pieces of data, called arguments and performing
some tasks with them.
➢ Then the functions returns a value that indicates the
results of the tasks complete within the function.

Function Hypotenuse (A As Double, B As Double) As Double


Sqr(A^2 + B^2)
End Function
Property Procedures
• A property procedure is used to create and
manipulate custom properties.
• It is used to create read only properties for Forms,
Standard modules and Class modules.
• Visual Basic provides three kind of property
procedures-
•Let procedure that sets the value of a property,
•Get procedure that returns the value of a
property, and
•Set procedure that sets the references to an
object.
➢ The Add Procedure option is chosen from the Tools
menu, which opens an Add Procedure dialog box as
shown in the figure given below.
➢ The name of the procedure is typed in the Name
textbox
➢ Under Type, Sub is selected to create a Sub
procedure, Function to create a Function procedure
or Property to create a Property procedure.
➢ Under Scope, Public is selected to create a procedure
that can be invoked outside the module, or Private to
create a procedure that can be invoked only from
within the module.
Branching and Looping Statements
• Branching and looping statements help us to control
the flow of the program/statements.
• repeat the execution of a particular block of
statements depending upon the logical expression in
branching
• Branching /Decision making structures require that
the programmer specify one or more conditions to be
evaluated or tested by the program.
Branching& Looping Statements in VB
If...Then Statement ( Simple If)
• If...Then statements is the basic statements in
programming.
• It allows us to check a particular condition
• Based on that condition following statement will
be executed.
• It focus only on true part of that condition not on
the false part.
• Syntax :
If <condition> Then
Statements to be executed
End If
Example for If… else
If age>18) then
Msgbox (“you are eligible to vote”)
Endif
If...Then Else Statement
• Next level of If..else statement
• This statement is having both the cases of True
and false statement…
• First it executes the expression, based on the
result of that expression True part or false part
gets executed.
• If a particular condition is satisfied, statement
following the if statement will be executed.
• Not Satisfied- Else part will be executed.
Flow Chart & Syntax
Syntax :
If condition Then
statement
Else
other statement
End If

Ex :
If (age>18)then
Msgbox “ eligible to vote
Else
Msgbox” Not Eligible to vote”
Endif
Flow Chart & Syntax for IF then elseif ….(Many)
Syntax & Example : IF elseif..Endif
• Syntax : • Example
If user= “Prabhu” Then
If condition Then msgbox “hi, Prabhu”
statement ElseIf user= “Priya” Then
ElseIf condition Then msgbox “hi, Priya”
other statement ElseIf user= “Ram” Then
ElseIf condition Then msgbox “hi, Ram”
other statement Else
Else msgbox “hi Gita”
default statement End If
End If
Nested If-Else Statement
• In nested If-Else statement, the defined
If condition returns true then it will enter into
the body of condition and perform
another if…else condition checking based on
our requirements.
NESTED IF –FLOW CHART
Syntax & Example
If x > y Then
If condition Then
If x >= 10 Then
If nested_condition_1 Then
msgbox("x value greater than or equal to 10")
// Statements to Execute
Else
Else
msgbox ("x value less than 10")
// Statements to Execute
End IF
End If
Else
Else
If y <= 20 Then
If nested_condition_2 Then
msgbox ("y value less than or equal to 20")
// Statements to Execute
Else
Else
msgbox("y value greater than 20")
// Statements to Execute
End If
End If
End If
End If
msgbox("Press Enter Key to Exit..")
Select Case Statement
• Another way to control the program flow, that
is, the Select Case control structure.
• The Select Case control structure is slightly
different from the If....ElseIf control structure.
• The difference is that the Select Case control
structure can handle conditions in an easier
manner than the If...Then...ElseIf control
structure.
Example for Select Case
Syntax : Select Case
Select Case expression
Case value1
statements-1
Case value2
statements-2
Case Else
Default Statement
End Select
Do While
Do While condition
' Statements till true
Loop
For ..Next Loops
• SYNTAX :
For counterVariable = fromValue To toValue
VB Statements...

Next counterVariable

Example :

Dim i as integer

For i = 1 To 10

Print “Hello”

Next i
Examples : For …. Next
Dim x As Integer Dim x As Integer
For x = 1 To 50 For x = 1 To 50 Step 2
Print x Print x
Next Next
Output : ? Output: ?
x Print X Next x Print X step 2
Do Loops
• Some Do...Loops first executes the statements and then
test the condition after each execution.
• Repeats a block of statements while
a Boolean condition is True or until the condition
becomes False.
• Can test condition only one time, at either the start or
the end of the loop.
• If you test condition at the start of the loop (in
the Do statement), the loop might not run even one
time.
• If you test at the end of the loop (in
the Loop statement), the loop always runs at least one
time.
Forms of Do loop

Do
Do While <condition >
statement-block
statement-block
Loop
Loop
While <condition >

Do
statement-block Do Until <condition>
Loop statement-block
Until <condition> Loop
Do Loop
N=10 n=n+10 Loop
Example : for Do Until Loops
Dim num As integer
num=0
Do Until num > 10
number = number + 1
Print number
Loop
Num Number= number +1 Print number
Example for While … Wend Loops..

Dim number As Integer


number = 1
While number <=10
number = number + 1
Wend
Print number
With...End With statement
➢When properties set for objects or methods are
called, a lot of coding is included that acts on the
same object.
➢It is easier to read the code by implementing the
With...End With statement.
➢Multiple properties can be set and multiple
methods can be called by using the With...End
With statement.
Example
The code is executed more quickly and efficiently
as the object is evaluated only once. The concept
can be clearly understood with following example.

With Text1
.Font.Size = 14
.Font.Bold = True
.ForeColor = vbRed
.Height = 230
.Text = "Hello World"
End With
Arrays
✓ An array is a consecutive group of memory locations
that all have the same name and the same type.
✓ To refer to a particular location or element in the array,
we specify the array name and the array element
position number.
✓ Individual elements of an array are identified using an
index.
✓ Arrays have upper and lower bounds and the elements
have to lie within those bounds.
✓ Each index number in an array is allocated individual
memory space and therefore users must avoid
declaring arrays of larger size than required.
Declaring arrays
➢ Arrays occupy space in memory.
➢ The programmer specifies the array type and the number of
elements required by the array so that the compiler may
reserve the appropriate amount of memory.
➢ There are two types of arrays in Visual Basic namely:
➢Fixed-size array : The size of array always remains the
same-size doesn't change during the program execution.
➢Dynamic array : The size of the array can be changed
at the run time- size changes during the program
execution
Fixed-sized Arrays
➢ When an upper bound is specified in the
declaration, a Fixed-array is created.
➢ The upper limit should always be within the
range of long data type.

Declaring a fixed-array

Dim numbers(9) As Integer


• numbers is the name of the array, and the
number 6 included in the parentheses is the
upper limit of the array. The above declaration
creates an array with 6 elements, with index
numbers running from 0 to 5.

• If we want to specify the lower limit, then the


parentheses should include both the lower and
upper limit along with the To keyword. An
example for this is given below.

• Dim numbers (1 To 10) As Integer


Dim lengths(1 to 10) As Integer
• In the above statement, an array of 10 elements
is declared but with indexes running from 1 to
10.
• A public array can be declared using the
keyword Public instead of Dim as shown
below.
Multidimensional Arrays
Arrays can have multiple dimensions.
• A common use of multidimensional arrays is to
represent tables of values consisting of
information arranged in rows and columns.
• To identify a particular table element, we must
specify two indexes: The first (by convention)
identifies the element's row and the second (by
convention) identifies the element's column.
• Tables or arrays that require two indexes to
identify a particular element are called two
dimensional arrays.
Multidimensional Arrays
• Note that multidimensional arrays can have more than two
dimensions. Visual Basic supports at least 60 array
dimensions, but most people will need to use more than two or
three dimensional-arrays.
• The following statement declares a two-dimensional array 50
by 50 array within a procedure.
• Dim AvgMarks ( 50, 50)
• It is also possible to define the lower limits for one or both the
dimensions as for fixed size arrays. An example for this is
given here.
• Dim Marks ( 101 To 200, 1 To 100)
• An example for three dimensional-array with defined lower
limits is given below.
• Dim Details( 101 To 200, 1 To 100, 1 To 100)
Static and dynamic arrays
• Static arrays must include a fixed number of
items, and this number must be known at
compile time so that the compiler can set aside
the necessary amount of memory.
• You create a static array using a Dim statement
with a constant argument:
• ' This is a static array.
Dim Names(100) As String
Constants
➢ Constants are named storage locations in memory, the value of
which does not change during program Execution.

➢ They remain the same throughout the program execution.

➢ When the user wants to use a value that never changes, a


constant can be declared and created.

➢ The Const statement is used to create a constant. Constants can


be declared in local, form, module or global scope and can be
public or private as for variables.

➢ Constants can be declared as illustrated below.

Public Const gravityconstant As Single = 9.81


Data Type Conversion
• Visual Basic functions either to convert a string into an integer or

vice versa and many more conversion functions. A complete

listing of all the conversions offered by Visual Basic is listed

below.
Boolean Cbool Integer Cint

Byte Cbyte Long CLng
Currency Ccur Single CSng
Date Cdate String CStr
Decimals Cdec Variant Cvar
Double CDbl Error CVErr
Visual Basic Operators
• Arithmetic Operators
• Assignment Operators
• Logical/Bitwise Operators
• Comparison Operators
• Concatenation Operators
Arithmetic Operators
Operator Description Example (a = 6, b = 3)
+ It will add two operands. a+b=9
- It will subtract two operands. a-b=3
* It will multiply two operands. a * b = 18
/ It divides two numbers and a/b=2
returns a floating-point result.
\ It divides two numbers and a\b=2
returns an integer result.
Mod It divides two numbers and a Mod b = 0
returns only the remainder.
^ It raises a number to the power of a ^ b = 216
another number.
Assignment Operators
Operator Description Example (a=20)
= It will assign a value to a a=3
variable or property.
+= It will perform the addition of a += 10 equals to a =
left and right operands and a + 10
assign a result to the left
operand.
-= It will perform a subtraction of a - = 10 equals to a =
left and right operands and a - 10
assign a result to the left
operand.
*= It will perform a multiplication a *= 10 equals to a =
of left and right operands and a * 10
assign a result to the left
operand.
Assignment Operators
Operator Description Example (a=20)
/= It will perform a division of a /= 10 equals to a =
left and right operands and a / 10
assign the floating-point result
to the left operand.
\= It will perform a division of a \= 10 equals to a =
left and right operands and a \ 10
assign the integer result to the
left operand.
^= It will raise the value of a a ^= 10 equals to a =
variable to the power of a ^ 10
expression and assigns the
result back to the variable.
Logical / Bitwise Operators

Operator Description Example (a = True, b =


False)
And It will return true if both operands are a And b = False
non zero.
Or It will return true if any one operand a Or b = True
becomes a non zero.
Not It will return the reverse of a logical Not(a And b) = FALSE
state that means if both operands are
non zero then it will return false.
A B OR AND
T T T T
T F T F
F T T F
F F F F
Comparison Operators
Operator Description Example (a = 10, b = 5)
< It will return true if right operand greater a < b = False
than left operand.

<= It will return true if right operand greater a <= b = False


than or equal to the left operand.

> It will return true if left operand greater a > b = True


than the right operand.

>= It will return true if left operand greater a >= b = True


than or equal to the right operand.

= It will return true if both operands are a = b = False


equal.

<> It will return true if both operands are not a < > b = True
equal.
Concatenation Operators

Operator Description Example (a = Hello,


b = World)
& It will concatenate given two a & b = HelloWorld
expressions.
+ It can be used to add two numbers or a + b = HelloWorld
concatenate two string expressions.
String functions in VB
Function Usage Example

Len (“string”) length of the specified string Len (“visual”) = 6

Right (“string”, n) Returns number of characters from the Right(“Visual Basic”, 4) = asic
right side of a string.

Left(“string”, n) Returns number of characters from the Left (“Visual Basic”, 4) =


left side of a string. Visu

Ltrim(“string”) Removes leading blank spaces from a Ltrim (“ Visual Basic”)=


string. Visual basic

Rtrim(“string”) Removes trailing blank spaces from a Rtrim (“Visual Basic ”) =


string. Visual basic

trim(“string”) Removes both leading and trailing Trim$(" Visual Basic ")=
blank spaces from a string. Visual Basic
Mid(string, position, n) Mid function extracts a Mid(“Visual Basic”, 4, 6) =
substring from the original ual Bas
phrase or string.
Instr(n, original, embedded) Specifies location of substring Instr(1, “Visual Basic”,”
from the original string . Basic”)=8

Ucase (String) converts all the characters of a Ucase(“Visual Basic”)


string to capital letters =VISUAL BASIC

Lcase (String) converts all the characters of a Lcase(“Visual Basic”) =visual


string to small letters. basic

Chr(ASCII value) returns the character that Chr(65)=A,


corresponds to an ASCII code

Asc(string) converts an ASCII character or Asc(A)=65


symbol to the corresponding
ASCII code
String(n,"Character") Prints the character ‘n’ number String(30, "#") - Prints # 30
of times Times
Built-in Functions
• A function is similar to a procedure but the
main purpose of the function is to accept a
certain input from the user and return a value.
• There are two types of functions in VB6,
– built-in functions (or internal functions)
– functions created by the programmers.
MsgBox ( ) Function
• MsgBox is to produce a pop-up message box
that prompt the user to click on a command
button
• Syntax :
X Style
=MsgBox(Prompt,Style
Value Value, Title)
Named Constant Buttons Displayed
0 vbOkOnly Ok button
1 vbOkCancel Ok and Cancel buttons
Abort, Retry and Ignore
2 vbAbortRetryIgnore
buttons.
Yes, No and Cancel
3 vbYesNoCancel
buttons
4 vbYesNo Yes and No buttons
5 vbRetryCancel Retry and Cancel buttons
msgbox() Examples
• testmsg = MsgBox("Click to test", 1, "Test
message")

• Another Example:
Value Named Constant
16 vbCritical
3 vbQuestion
48 vbExclamation
64 vbInformation
Example for Inputbox()
• userMsg = InputBox(“Enter Student’s Date of Birth”)

• userMsg = InputBox("What is your message?", "Message


Entry Form", "Enter your messge here", 500, 700)
The InputBox( ) Function
• An InputBox( ) function will display a message box where the
user can enter a value or a message in the form of text. The
format is
• msg=InputBox(Prompt, Title, default_text, x-position, y-
position)
• Prompt - The message displayed normally as a question asked.
• Title - The title of the Input Box.
• default-text- The default text that appears in the input field where
users can use it as his intended input or he may change to the
message he wish to key in.
• x-position and y-position - the position or the coordinate of the
input box.

You might also like