variables
variables are named memory locations used
to store values during program execution.
Visual basic Data
types
1. Byte
2. Integer
3. Long
4. Single
5. Double
6. Currency
7. Boolean
8. Date
9. Object
10. String
11. variant
Byte
occupies 8 bits( 1 byte ) of memory.
contain unsigned whole number.
ranges from 0 to 255
negative numbers and value larger
than 255 are not allowed.
very fast for counting and holding
small numbers.
Integer
occupies 16 bits ( 2 byes ) of memory
Hold whole numbers between -32,768
to 32,767
not appropriate for calculations
involving fractional portion of numbers.
fast when used in calculations and
loops.
Long
long integers can be assigned much larger and
much smaller values than integers.
occupies 32 bits ( 4 bytes ) of memory.
Hold positive whole numbers and negative
numbers in the range
-2,147,483,648 to 2,147,483,647
Slower because computer must move more data
into and out of memory locations.
should not be used for simple counting tasks
Single
contains floating-point numbers.
occupies 32 bits ( 4 bytes ) of memory.
Small numbers stored with good
precision.
Appropriate for very precise financial
and scientific calculations.
Double
occupies 64 bits ( 8 bytes ) of memory.
Hold extremely large and small
flaoting-point numbers.
used for calculations requiring extreme
precision.
Calculations involving double data type
are slow.
currency
reserved for storing monitory values
such as bank account balances, prices.
currency values stored as very large
integer values that contain no decimal
points.
Visual Basic divides the integer value
by 10000.
Boolean
Boolean variables accepts True or
False values.
stored internally as integer numbers.
True - -1
False - 0
The default value is 0 (False)
code written with Booleans is easier to
understand.
Date
date variables contains date and time
data.
Occupies 8 bytes of memory.
Stored internally as floating-point
number.
String
string variable stores text data such
as name, addresses.
Also contains non-printable characters
such as Ctrl+G
String
Fixed length Strings
contains at most approximately
65,000 characters
declaration:
Dim sFixed As String * 10
String
variable length Strings
contains at most approximately 2
billion characters
declaration:
Dim sVariable As String
String
Fixed Width Strings
Fixed-width strings are padded with
spaces to fit the width defined for the
string
example:
if sFixed is Windstar , data actually
stored as
Windstar
String
various trim functions to remove
unwanted spaces.
Ltrim - removes leading spaces
Rtrim - removes trailing spaces.
Trim - removes both leading and
trailing spaces.
Object
Visual Basic provides object data type
to work with data other than numbers
and letters.
object variable
provide a lot of flexibility in Visual
Basic projects
Object
example:
private sub Form-load()
frmBuddy. Show
Call UpdateCaptions ( Me, txtCaption1 )
End Sub
Public Sub UpdateCaptions ( frm As Object, txt As
Object)
txt.Text = frm.Caption
End Sub
Object
specific object type run faster than generic
object type.
private sub Form-load()
frmBuddy. Show
Call UpdateCaptions ( Me, txtCaption1 )
End Sub
Public Sub UpdateCaptions ( frm As Form, txt As
TextBox)
txt.Text = frm.Caption
End Sub
Object
Object-Oriented and Object-Based Languages.
Visual Basic is not an object-oriented
language but an Object-based programming
language.
there are 2 main sources of the objects:
1. Built-in Object types and generic object data
type
example: Form, TextBox
2. Objects created by user through the use of
classes
Object
objects are natural way to manage forms
and other components of Visual Basic
application
built-in objects provide great way to write
reusable code.
Variant
variant is default data type in Visual Basic
variant can accept any value.
adjust the internal memory storage required
to accommodate the value assigned to the
variant variable.
requires more storage space and consumes
more CPU cycles at runtime than other data
types
Declaring Variables
2 methods :
1. implicit declaration
2. explicit declaration
implicit declaration
automatically creates variant for each identifier it
recognizes as a variable in an application
Example:
Private Sub cmdCombine_Click()
FirstName= txtFirstName. Text
LastName = txtLastName. Text
txtFullName = FirstName & & LastName
End Sub
Declaring Variables
Explicitdeclaration
using keywords Dim, Static, Private, and Public
Syntax
Dim VariableName As DataType
StaticVariableName As DataType
Private VariableName As DataType
public VariableName As DataType
VB reserves the amount of memory required to hold
the variable when the declaration statement is executed.
not possible to change a variable datatype after
declaration.
Declaring Variables
It is possible to convert value of a variable
and asign to another variable.
explicit variable declarations are
unambiguous
example:
Private Sub cmdCombine_Click( )
Dim FirstName As String
FirstName = txtFirstName.Text
End Sub
Declaring Variables
Implicit declarations lead to bugs in your code.
Private Sub Form_Load ( )
Department = Manufacturing
Superviser = Joe
txtDepartment = Department
txtSupervisor = Superviser
End Sub
VB simply creates a new variant named
txtSuperviser
and ssigns the value Superviser to it.
Declaring Variables
Comparison of Implicit and Explicit Variable
implicit declaration is not very efficient as
the variant data type require more data
storage.
computer consumes more time
17 percentage performance enhancement
when using explicitly declared variables.
Declaring Variables
Forcing explicit declaration
Option Explicit
Option Explicit statement is used to force
explicit declaration.
it is inserted at the top of a module
it explicitly declare all variables in the
module as variant
requiring a variable declaration is a good
idea in most VB applications. To do this
Editor tab option dialog box Require
Variable Declaration check box
Declaring Variables
Naming Convention
The Reddick Naming convention
authored by Greg Reddick
3 or 4 character prefix attached to the base
name of the objects and variables in Vb
application.
example: txtLastName, strCustomer,
boolActive, fActive( flag value )
Variable Scope and Lifetime
Scope
the visibility of a variable or procedure is called its
scope.
variable scope is determined by the variables
declaration.
a variable that can be seen and used by any procedure
in the application is said to have public scope.
a variable that is usable by a single pr0cedure is said
to have private scope.
variables declared within a procedure are local to that
procedure and cannot be used or referenced outside that
procedure.
Variable Scope and Lifetime
Scope
Dim keyword is used to define the variable.
Dim is shorthand for dimension that instructs VB
to allocate enough memory to contain the variable
that follows the Dim .
Public keyword is used to make a variable visible
throughout an application
public can be used only at module level and
cannot be used within a procedure
used only in standard modules that are not part of
a form.
Variable Scope and Lifetime
Scope
every variable declared in the general
section of the standard module is public unless
the private keyword is used
Private restricts the visibility of a variable to
the module in which the variable is declared
Variable Scope and Lifetime
Lifetime
lifetime is determined by the location of variables
declaration.
determines when it is accessible to the application.
by default, procedure level variables exist only
while the procedure is executing.
a variable declared in the declarations section of a
forms module exists as long as the form is open.
public variables are available as soon as the VB
application starts up and persists until the program
is shut down and removed from memory.
Variable Scope and Lifetime
Lifetime
Private variables, declared at the top of
standard modules, accessible through out the
application.
the Static keyword variables persist between
calls to the procedure
static variables are not re-created each time
the procedure is called.
Converting between
data types
VB automatically converts between the data types in the expression.
example:
Public Sub Conversion()
Dim sStr As String
Dim dDbl As Double
sStr = 12345.67890
dDbl = sStr
MsgBox Value of dDbl: & dDbl & vbCrLf & TypeName(dDbl) : &
TypeName( dDbl )
End Sub
message box reprts the value of dDbl as 12345.67890 and data type as
double.
Converting between
data types
automatic conversion is called coercion .
coercion will generate runtime error.
VB truncates values when fractional values
assigned to integers.
VBA language provide built-in conversion
functions.
Converting between
data types
automatic conversion is called coercion .
coercion will generate runtime error.
VB truncates values when fractional values
assigned to integers.
VBA language provide built-in conversion
functions.
data converted by the VBA conversion
functions must be appropriate for the
destination variable
Arrays
arrays is a series of variables of the same type
index number is used to denote the array
elements
Declaring arrays
2 types:
fixed-size arrays - number of elements in the
array does not vary during execution.
variable-size arrays - number of elements in
the array can vary during execution.
Arrays
syntax of fixed-size array declaration:
Dim ArrayName ( [ LowerBound To
[UpperBound]]) [As DataType ]
ArrayName name of the array
UpperBound and LowerBound highest and
lowest index values.
name of the array is any valid Visual Basic data
types.
if no LowerBound value is provided, Vb
automatically assigns 0 .
Arrays
the Datatype of an array can be any valid VB
data type.
if the data type portion of the declaration is
omitted, an array of variant is created.
Array Limitations
all the elements of array must be of the
same data type.
Arrays limitations
Runtime errors
caused by hardware failures of one type or another.
example: failure of hard disk
Run-time errorsare those that appear only after
you compile and run your code. These involve code
that may appear to be correct in that it has no syntax
errors, but that will not execute. For example, you
might correctly write a line of code to open a file. But
if the file is corrupted, the application cannot carry
out theOpenfunction, and it stops running. You can
fix most run-time errors by rewriting the faulty code,
and then recompiling and rerunning it.
Dealing with
Runtime errors
hardware failures are easly to detected and resolved
memory errors are tricky to deal with
memory error causes the application slow down
detecting and avoiding hardware-related runtime
errors is difficult.
there is API ( Windows application programming
interface ) calls that report on the current status of
computers hardware and accessories.
Most common hardware problems can be avoid
through these API calls.
Avoiding errors
include only one variable declaration in a
single line of code
grouping variable declarations leads to
difficulty in determine its data type.
variables of same type can be group
together
within each data type group , arrange
variable names in alphabetical order. this
makes it easy to see all variables at a glance.
Module option
Module option
General option dialog box contains different methods to
trap errors in VBA code.
Break On All Errors:
o Since moving one step at a time can be painful, there is
another debugging tool available called breakpoint.
oWhen you run a program, the execution stops at the
selected line and you can check the values. Visual basic
shows a large brown dot in the margin to remind that there
is a breakpoint in that line.
o For example if you wanted to check the volume
calculation, you would put a breakpoint in the line for
volume calculation.
Module option
You can put a breakpoint by clicking in gray
area in the left of the code. If you click once
you will see red DOT, which indicates
breakpoint. To clear the breakpoint, simply
click on the DOT again. When you run the
code, it will stop at the line where a breakpoint
is placed. You can use multiple breakpoints in
a code.
Module option
Break in Class Module:
class modules are developed independently
errors occur in the class modules project
Break on Unhandled Errors
this option causes program execution stop
on errors that are not handled by VBA code.
Module option
Compile on Demand:
this option instructs VB to compile modules
only when their functions are required .
when this option is unchecked , all modules
are compiled any time any function is called.
Takes more time
Background Compile
this option instructs VB to perform most of
the compilation in the background as possible.
Traditional Debugging
Techniques
2 techniques:
insert MsgBox statement to display the value of
variables, procedures , so on
insert Debug.Print statement to output messages
to the immediate window.
MsgBox
Sub MsgBoxCheck()
Dim i For i = 1 to 5
MsgBox I
Next I
End Sub
Traditional Debugging
Techniques
Uses of MsgBox
easy to use and can output any type of data
appears on the user interface. No need to open
immediate window.
simple
Problems of MsgBox
message boxes are modal
output appears on the user interface. Compiler
directives are used to suppress messages from the
user.
Traditional Debugging
Techniques
Debug.Print
used to output messages to the Immediate
window
Print is the method of Debug object.
example:
Traditional Debugging
Techniques
Traditional Debugging
Techniques
Benefits -Debug.Print
output goes to the Immediate window:
no need of compiler directives to suppress the
messages from the user
Problems
there is no way to save or print the contents of
the Immediate window. But you can copy the
contents to the windows clipboard
Long strings do not wrap in the immediate
window unless concatenate vbCrLf
Traditional Debugging
Techniques
Benefits -Debug.Print
output goes to the Immediate window:
no need of compiler directives to suppress the messages from
the user
Problems
there is no way to save or print the contents of the Immediate
window. But you can copy the contents to the windows clipboard
Long strings do not wrap in the immediate window unless
concatenate vbCrLf
immediate window must be brought to the inorder to view its
output.
more number of Debug.Print statement can slow the application.
Visual Basic Debugging Tools
tasks involving debugging a Visual Basic
application
Execute procedures:
suspending execution:
Single- stepping through code:
Examine variables:
Redirect program flow:
Visual Basic Debugging Tools
Debug Toolbar
debugging tools are located on the Debug
toolbar.
to open this toolbar:-
right click on existing toolbar and select
Debug from toolbar drop-down list
or
choose Toolbar command from View menu
and select Debug
Debug toolbar is context sensitive
Visual Basic Debugging Tools
Debug Toolbar
Visual Basic Debugging Tools
Suspending execution with BreakPoints
by setting beakpoints, execution can be