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

Introduction To VB

This document discusses variables and data types in Visual Basic. It covers declaring variables, both explicitly and implicitly. Numeric, string, date, and other variable types are described along with their properties. Arrays and collections are also summarized as common data structures in Visual Basic for organizing multiple values. The document concludes with an overview of procedures like subroutines and functions for logically organizing code.

Uploaded by

Pardeep Bogra
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views

Introduction To VB

This document discusses variables and data types in Visual Basic. It covers declaring variables, both explicitly and implicitly. Numeric, string, date, and other variable types are described along with their properties. Arrays and collections are also summarized as common data structures in Visual Basic for organizing multiple values. The document concludes with an overview of procedures like subroutines and functions for logically organizing code.

Uploaded by

Pardeep Bogra
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 41

Declaring Variables

• In most programming languages , variables must be


declared in advance. But one of the most popular,
yet intensely criticized, feature of BASIC was that it
did not force the programmer to declare all
variables. In VISUAL BASIC programmer have
both options. Programmer can choose weather he
wants to force the declaration by compiler or not.
By default variable declaration is not compulsory.
We can write “OPTION EXPLICIT” at the top to
force the variable declaration.
• Explicit Declarions
Dim RollNo as Integer
Dim Msg as String

• Implicit Declarions
Dim var1, var2
Variable name conventions
• Must begin with a letter
• Must not exceed 255 character
• Must be unique within its scope
• Cannot contain a period or any other
type declaration character
Types of variables
• Numeric
• String
• Boolean
• Date
• Object
• Variant
Numeric Data Types
• Byte ( 0 – 255 )
• Integer ( -32,768 to 32,767 )
• Long ( -2,147,483,648 to 2,147,483,647 )
• Single ( -3.402823e38 to –1.401298e-45 )
• Double
(-1.79769313486232e308 to –4.94065645841247e-324)
( 4.94065645841247e-324 to 1.79769313486232e308 )
• Currency
(-922,337,203,685,477.5808 to 922,337,203,685,477.5807)
String Data Type
• A string variable can hold up to 2GB of
data
• Fixed Length Strings
Dim msg as string * 1000

Now if we store less than 1000 characters


in msg then the variable is padded with the
spaces.
Boolean Data Type
• The Boolean data type stores True/False
values. Visual Basic allocates two bytes to
this data type.
Dim flag as Boolean
If flag then
statements
End if
Date Data Type
• A variable declared as date can store both date and
time values. Date and time values are stored
internally in a special format. They are Double
precision numbers: the integer part represents the
date and the fractional part represents the time.The
date format is determined by the Regional Settings
(control panel). In the United States, it is mm/dd/yy
and in other countries it is dd/mm/yy. But if user
enters in wrong format it automatically swap the
month and day value to make it correct entry.
Dim Test as Date

Test = “24/06/1977”
Test = “12:40:34 AM”
Test = “24/06/1977 12:40:34 AM”
Test = #24/06/1977 12:40:34 AM#
Test = Date( )
Object Data Type
• An object variable refers to one of the
Visual Basic’s many objects.

Dim a as CommandButton, b as label


Set a = cmdAdd
Set b = lblName
a.caption = “New”
Variant Data Type
• This is the most flexible data type because it can
accommodate all other data types. If you assign
integer value to a variant Visual Basic treats it like
integer if you store string it is treated as string.
Variants can also hold different data in the course
of the same program.

Dim Var1
Dim var1 as variant
Data Type definition characters
Symbol Data Type Example
$ String A$, msg$
% Integer Phone%
& Long Color&
! Single Distance!
# Double ExactDistance#
Converting variable types
• CBool - Boolean • Clng - Long
• CByte - Byte • Ssng - Single
• CCur - Currency • CStr - String
• CDate - Date • Cvar - Variant
• CDbl – Double • CVerr - Error
• CInt - Integer
User Defined Data Type
Type Student
RollNo as integer
Name as string
End Type

Dim S as Student
S.RollNo = 1001
S.Name = “sumit”

Dim S(10) as Student


Special Values
• The Empty value
• The Null value
• The Nothing value
• The Error value
The Empty value
• If a variable has been declared but has not
yet been assigned a value, its value is Empty.
The Empty value is different from zero length
string.

If isEmpty (var) then MsgBox(“Variable has not been


initialized”)

We can also assign Empty value to a variable.


Var = Empty
The Null value
• Null is used in database applications to
indicate that a field does not contain data.
The Null value is different from Empty value.
A variable of type is never Null unless you
assign Null value to it. Uninitialized variables
that refers to database field are Null not
Empty.
• isNull( ) function can be used to check that a
field contains a value or not.
The Nothing value
• The nothing value is used with objects
and indicates that an object variable has
not been initialized.

Set A = CreateObject(Excel.Application)
if (A is nothing) then
Statements
End if
The Error value
• This value allows you to write function that
return variant types or errors. If the function
carries out its operation successfully, the result
is returned otherwise it can return an error
value.

Result = myFunction(arguments)
If isError(result) then
{Handle Error}
Else
{Use Result}
End if
Arrays
• A standard structure for storing data in
any programming language is an Array.
Whereas individual variables can hold
single values, arrays can hold a sets of
related data. An array has a name, as
does a variable and the values stored in
it can be accessed by an index.
Declaring Arrays
• Dim salary(10) as integer
• Dim salary(1 to 10) as integer
• Dim salary(-10 to 10) as integer
• Dim marks(1 to 5, 1 to 4) as integer
Arrays of Arrays
• One of the possibilities introduced to the
Visual Basic language with the variant
data type if that of creating complex
structures, such as arrays of arrays. If
an array is declared as variant, you can
assign other data types including
arrays.
Example: Arrays of Arrays
• Dim intArray(1 to 10) as integer
• Dim strArray(1 to 10) as string
• Dim BigArray(1 to 2) as variant

• BigArray(1) = intArray ( )
• BigArray(2) = strArray ( )

• To access 3rd element in strArray


• BigArray(2)(3)
Dynamic Arrays
• Sometimes you may not know how
large to make an array. Instead of
making it large enough to hold the
maximum number of data (in which
most the entries will be empty), you can
create an dynamic array.

• Dim a() as integer


• Later in a program when you know how
elements you want to store in the you
can use ReDim to tell its actual size.
ReDim can be used only in procedure
part it cannot be a part of declaration.
ReDim a(N)
• Each time when you use ReDim values
stored in array will be lost. If you want to
preserve previous values and you want
to increase the size of array then you
can use ReDim like :-
ReDim preserve a(ubound(a)+n)
Collections
• Arrays are convenient way for storing related
data, but accessing individual elements is can
be a problem. To print the temperature in
Atlanta, for instance, you would have to know
the index corresponds to Atlanta. If you didn’t
you have to scan each element in the array
until you found Atlanta. It can be done very
easily with the help of Collections.

Dim Temperature as New Collection


Methods & Property of collection
• Add Method: Adds items to the
collection
• Remove method: Deletes an item from
collection by index number or key
• Item method: Returns an item by index
number or key
• Count property: Returns the number of
items in the collection
Add Method
• Collection.Add Value, Key, Before, After
• To add a new element to a collection, assign
its value, key which are compulsory
arguments. Before and after are optional. We
can use any one of them if we want to insert
new element before or after any existing
element.
• Temperatures.Add 78, “Delhi”
• Temperatures.Add 78, “Delhi”, “Goa”
• Temperatures.Add 78, “Delhi”, ,“Goa”
• Temperatures.Add 78, “Delhi”, after:= “Goa”
Remove, Return & Count
• Temperatures.Remove “Delhi”
• Temperatures.Remove 5

• T1 = Temperatures.item(“Delhi”)
• T1 = Temperatures.item(6)

• C = Temperatures.count
Processing collection items
For each city in temperatures
total = total + city
Next

For city = 1 to temperatures.count


total = total + city
Next city
Procedures
• Procedures are useful for repeated
tasks or/and are used to break long
application into small unit. There are
two types or procedures.
• Sub-routine & Functions
Sub-routines
• A sub-routine is a block of statements that
carries out a well-defined task. The block of
statements is placed with a pair of Sub/End
Sub statements and can be invoked by name.

Sub Name(arguments )
statements
End Sub
Event Handlers
• An Event Handler is a short segment of code that is
executed each time an external condition triggers the
event. When the user clicks a control, the control’s
click event handler executes. This handler is nothing
more than a sub-routine, which performs all actions
you want to perform when the control is clicked. It is
separate from the rest of code and does not have to
know what would happen if another control was
clicked or if the same control was double clicked.

Sub ControlName_Event ( arguments)


Statements
End Sub
Functions
• A function is similar to a sub-routine, but a
function returns a result. Subroutines performs
a task and do not report anything to the calling
program. Functions commonly carry out
calculations and report results.The statements
that make up a function are placed in a pair of
Function/ End Function statements.
Function Name(arguments) as returnType
Statements
Function_Name = return Value
End Function
Calling Procedures
• Call Subroutine_Name(arg1, arg2)
• Subroutine_Name arg1, arg2

• Var = Function_Name(arg1, arg2)


• Var = Function1(arg) + Function2(arg)
• MsgBox “Hello”
• Call Function_Name()
Passing Arguments
• By Reference
Function Add(A as integer, B as integer) …

• By Value
Function Add(ByVal A as integer, ByVal B
as integer) …
Optional Arguments
Function Test(a as string, optional b as double) as double
If IsMissing(b) Then
statements
Else
statements
End if
End Function

Var = Test(String var/value, Double var/value )


Var = Test(String var/value )

Var = TestFunction(value1, , value3)


Optional default arguments
Function Test(a as string, optional b=0) as double
If IsMissing(b) Then
statements
Else
statements
End if
End Function

Var = Test(String var/value, Double var/value )


Var = Test(String var/value )
Variable number of arguments
Sub Name(ParamArray A( ) )
For each x in A
Statements
Next x
End Sub

Here all the values of parameter will be stored


in array A. ParamArray is a keyword.
Named Arguments
• With the help of named arguments you
can pass values in any order.

Sub contact(name as string, Email as


string)

Contact(Email:=“[email protected]
m”, name:=“Pardeep”)
Returning arrays & Custom data type

Function Test(m( ) as double) as double( )


anArray = Test( s( ))

Function Test(arg) as CustomTypeName

You might also like