Visual Basic
Visual Basic
Form frm
Label lbl
Comment Green
Click occurs when the user clicks Modules - code in VB is stored in this form
anywhere on the form or control
3 Kinds on Modules
Initialize occurs when the form is first 1) Form Modules
generated a) simple application may contain a
single Form, and the code resides
Load occurs when the form is loaded
into the computer’s memory and in that Form module
displays on the screen b) As application grows, additional
Forms are added and there may
Dblclick occurs when the user be a common code to be executed
double-clicks the form or control in several Forms
Deactivate occurs when another form gets
the focus 2) Standard Modules
a) a separate module containing a
Unload occurs when the form is procedure created to implements
terminated from the computer’s the common code to avoid
memory
duplication of code
Resize occurs when the user changes
the size of a form 3) Class Modules
a) .CLS file name extension
Change occurs when the user changes b) foundation of object-oriented
the text inside a textbox
programming in Visual Basic
c) new objects can be created by
Procedure - section in the code window that writing code in class modules
holds assignment statements for control to d) Each Module can contain:
perform a specific task or action 1) Declarations - include
constant, type, variable,
Syntax - set of rules defining the proper use of and DLL procedure
programming language declarations
2) Procedures - sub function,
Syntax Error - result of violation of any of the or property procedure that
programming language rules contains pieces of code
that can be executed as a VB Data
unit ● Numeric - holds whole numbers
○ Integers - whole numbers and
The rules in naming elements in VB - variables, without decimal points
constants, controls, procedures, and so on: ○ Decimal - holds numbers with
1) A name must begin with a letter. decimal points that usually
2) Maybe as much as 255 characters long represent fractional values
3) Must not contain a space or an embedded ● Nonnumeric
period or typedeclaration characters used ○ Boolean - yes/no, true/false
to specify a data type; these are !, #, %, $, ○ String
&, and @. ○ Variant
4) Must not be a reserved word. ■ Data that can hold any kind
5) The dash, although legal, should be of data except for
avoided because it may be confused with fixed-length strings
the minus sign. ■ used as a storage area
when there is a need to
hold different kinds of data
Arithmetic Operators
● Follows EMDAS
Operation Symbol Notation
Addition + a+b
Subtraction - a-b
Multiplication * a*b
Division / a/b
(Floating)
Division | a\b
(Integer)
Exponentiation ^ a^b
Logical Operators
Variables ● Syntax:
● inserted as code statements Dim VariableName As DataType
● temporarily named storage areas inside Dim Var1, Var2, Var3 As DataType
the program’s memory that will hold data
Variable Declaration
● may declared in 2 locations:
○ General declarations - variables
declared here can be used within
the project but not in other parts of
the program
○ Option explicit statement - tells
Visual Basic that the rest of the
code in a module is to declare all
variables before they are used
● can be declared as:
○ implicit declaration
○ explicit declaration
○ option explicit
○ scope variables
Implicit Declaration
Option Explicit Declaration
● Assigns default variable type and value
● forces the user to declare all the variables
● Syntax:
● Option Explicit statement checks in the
variablenameSuffic = value
module for the usage of any undeclared
variables and reports an error to the user
Scope of Variable
● scope of a variable, procedure, or object
determines which part of the code in our
application is aware of the variable's
existence
● variable is declared in the general
declaration section of a Form and hence is
available to all the procedures
● Types:
○ procedure-level (local)
■ recognized only in the
procedure in which they are
declared
■ the values of its local
variables are lost and the
memory used by these
variables is freed and can
Explicit Declaration be reclaimed after the
● user has more control in manipulating the execution of procedure
variables ■ only available to the code
● variables are declared with a Dim inside the procedure and
statement to name the variable and its can be declared using the
type Dim statements
● As type clause in the Dim statement
allows defining the data type or object
type of the variable
○ Static
■ reinitialized each time
Visual Basic invokes a
procedure and therefore
retains or preserves value
even when a procedure
end
■ ideal for making controls
alternately visible or
invisible
■ Syntax: Constant Variable
Static VariableName As DataType ● variable whose value cannot be changed
● 2 kinds
○ Intrinsic or symbolic
■ commonly used features
are prefixed with vb
■ vbYesNo, vbOkOnly,
vbBlue, vbBackcolor,
vbChecked
○ Module-level ○ User-defined
■ available to all the ■ constants defined by
procedures in the module programmers
■ declared using the Public or ■ Syntax:
the Private keyword Const ConstantName = Value
■ Private module-level ■ Example:
● variable is declared Const PI = 3.14159
using a Private or a Global Const PI = 3.14159
Dim statement in
the declaration Sub Procedures
section of a ● placed in standard, class, and form
module—a standard modules
BAS module, a form ● when called, the statements between Sub
module, a class and End Sub are executed
module, and so on ● Syntax:
● visible only from [Private|Public] [Static] Sub ProcedureName (arglist)
. . .statement block…
within the module
End Sub
they belong to and
can't be accessed
Types of SP
from the outside
● Event Procedures
■ Syntax
○ procedure block that contains the
Public/Private VariableName As DataType
control's actual name, an
underscore (_), and the event
name
○ Example:
Private Sub Form_Load()
. . .statement block…
End Sub
● General Procedures
○ declared when several event ● Module - declared in the general
procedures perform the same declarations using the keyword Dim or
actions Private
● Local - declared in a procedure using
Function Procedures Dim or Static
● like sub procedures, except they return a
value to the calling procedure Types of Array
● especially useful for taking one or more ● Fixed-Size
pieces of data, called arguments, and ○ Syntax:
performing some tasks with them Dim/Public ArrayVariable(Length) As DataType
● the functions return a value that indicates Dim/Public ArrayVar(LL To UL) As DataType
the results of the tasks complete within the
function ● Multidimensional
● Example: ○ used to represent tables of values
Function Hypotenuse (A As Double, B As Double) As Double consisting of information arranged
Hypotenuse = sqr (A^2 + B^2)
in rows and columns
End Function
○ VB supports at least 60 array D
○ 2D array - arrays that require two
Property Procedures
indexes to identify a particular
● used to create and manipulate custom
element
properties
○ to identify a particular table
● used to create read-only properties for
element, specify two indexes:
Forms, Standard modules, and Class
■ first (by convention)
modules
identifies the element's row
● 3 Kinds:
■ second (by convention)
1) Property Let - sets the value of a
identifies the element's
property
column
2) Property Get - returns the value
○ Syntax:
of a property
Dim ArrayName(Sub1,Sub2) As DataType
3) Property Set - sets the references
Dim ArrayName(Low1 To Up1,Low2 To Up2) As _
to an object
DataType
Array
● consecutive group of memory locations
that all have the same name and the
● Static
same type
○ include a fixed number of items,
● to refer to a particular location or element
and this number must be known at
in the array, specify the array name and
compile time so that the compiler
the array element position number
can set aside the necessary
● individual elements of an array are all of
amount of memory
the same data types
○ Uses Dim statement with a
● have upper and lower bounds and the
constant argument
elements have to lie within those bounds
○ Syntax:
● individual elements of an array are
Dim arrayname(length) As datatype
identified using an index (starts at 0)
○ each index number in an array is
● Dynamic
allocated individual memory space
○ Can be resized during execution
and therefore users must evade
○ Uses ReDim statement to resize
declaring arrays of larger size than
○ re-creating a dynamic array,
required
○ its contents are reset to 0 (or to an
empty string) and it loses the data
Array may be declared as:
it contains
● Public - declared in a code module
○
if need to resize an array without
Sqr(number) number
losing its contents, use the ReDim
Preserve command Abs returns the absolute value of a
○ To destroy, use Erase statement Abs(number) number
○ Syntax:
Exp Exp of a number x is the value of
Dim arrayname() As Datatype
Exp(number) ex
Sub Main()
ReDim arrayname(length) As Datatype Fix like Int but when the number is
negative, it will return the
Note: Fix(number) smallest integer that is larger
● Comment statements begin with the than the number
keyword Rem or a single quote ('). Round rounds up a number to a certain
Round(n, m) number of decimal places
Mathematical Functions
● useful and important in programming String Functions
because very often there is a need to deal
Name & Syntax Function
with mathematical concepts in
programmings such as chance and Len returns an integer value
probability, variables, mathematical logic, equal to the length of a
calculations, coordinates, time intervals Len(“Phrase”) phrase or a sentence,
including the empty spaces.
Name & Function
Syntax Right extracts the right portion of
Right(“Phrase”, n) a phrase from n to the right
Rnd returns a random value between
Rnd or 0 and 1 Left extracts the left portion of a
Int(Rnd*n) randomize whole number Left(“Phrase”, n) phrase from n to the left
Int converts a number into an Ltrim trims the empty spaces of
integer by truncating its decimal the left portion of the
Int(number) part and the resulting integer is Ltrim(“Phrase”) phrase
the largest integer that is smaller
than the number Rtrim trims the empty spaces of
the right portion of the
Sqr computes the square root of a Rtrim(“Phrase”) phrase
Trim trims the empty spaces on
Trim(“Phrase”) both sides of the phrase Other date and time functions are
DateAdd, DateDiff, DatePart, DateSerial,
Mid extracts n numbers of DateValue, Day, Hour, Minute, Month,
characters in the string MonthName, Second, TimeSerial, TimeValue,
Mid(“Phrase”, position, n) from position Weekday, WeekdayName, and Year
InStr looks for a phrase that is
embedded within the Formatting Functions
Instr (n, “original phase”, original phrase from n and
“embedded phrase”) Name & Function
returns the starting position Syntax
of the embedded phrase
Tab display text (string or
Ucase converts all the characters numbers) at n away from the
Ucase(“Phrase”) of a string to capital letters Tab(n); x left border of the output form
Lcase converts all the characters Space specifies the number of
Lcase(“Phrase”) of a string to small letters. a; Space(n); b spaces between two
consecutive items
Str converts a number to a
Str(number) string Format can display numeric values in
Format(n, a built-in form or in a way
Val converts a string to a
“style defined by the user
Val(string) number
argument”)
Chr returns the string that
corresponds to an ASCII Predefined Format Function
Chr(charcode) code
General display number without comma
Asc converts an ASCII Number separators
character or symbol to the
Asc(Character) corresponding ASCII code Fixed display number without comma
separators and round to 2 decimal
String returns a character places
repeated the specified n
String(n,"Character") times. Standard display number with comma
separators and round to 2 decimal
vbCrLf Named combination of two abbreviations places
Constant carriage return and line feed
Currency display the number with the dollar
Date and Time Functions sign with comma separators and
Name Function round to 2 decimal places
Nesting Syntax:
Method 1
If condition1 Then
Statements
Else If condition2 Then
Statements
Else If condition3 Then
Statements
Else
Statements
End If
Method 2
If condition1 Then
Statements Example:
Else Select Case Age
If condition2 Then Case 5
Statements Category = "Five Year Old"
Else Case 13 To 19
If condition3 Then Category = "Teenager"
Statements Case 20 To 35, 50, 60 To 65
Else Category = "Special Adult"
Statements Case Is > 65
End If Category = "Senior Citizen"
End If Case Else
End If Category = "Everyone Else"
End Select
Key Trapping
● prevent the user from typing in Repetition Structures
meaningless characters (for example, ● allows the programmer to do an action
letters) into the text boxes expecting that is to be repeated until the given
numerical data condition at the beginning or end of the
● process of intercepting unacceptable loop is true
keystrokes
● done in the KeyPress procedure of an Do loop
object ● repeats a sequence of statements or
● If KeyAscii is an acceptable value, the procedures as long as the condition is true
program will do nothing. However, if ● condition set to this uses keywords such
KeyAscii is not acceptable, set KeyAscii as while or until and followed by the word
equal to zero and exit the procedure. do or loop
Doing this has the same result of not ● statement Exit Do will get you out of a loop
pressing a key at all. and transfer program control to the
Syntax: statement following the Loop statement
Sub Textbox_KeyPress (KeyAscii as Integer)
statements Do While …loop
End Sub ● used to execute statements until a certain
condition is met
● first checks the condition set to this and if
the condition is true then the proceeding
statements are executed
● it will not execute even once if the While
condition is violated (False) the first time
through
ASCII Characters
Char Char Char
0 Null 41 ) 64 @
8 backspace 42 * 65 - 90 A to Z
9 tab 43 + 91 [
10 new line 44 , 92 \
13 enter 45 - 93 ]
35 # 58 : 97 - 122 a to z
36 $ 59 ; 123 {
37 % 60 < 124 |
38 & 61 = 125 }
39 ‘ 62 > 126 ~
40 ( 63 ? 127 del
For…Next Loop
● used to make repetition of procedures or
Do Until…Loop Statement statements; it can give the same output as
● tests a condition for falsity the other repetition structure however the
● Statements in the body of a Do Until … structure is different
Loop are executed repeatedly as long as ● handles all the details of
the loop-continuation test evaluates to counter-controlled repetition
False ● using an Exit For statement will transfer
● will not be entered if the Until condition is program control to the statement following
already True on the first encounter the Next statement
● Syntax:
Do Until condition Syntax:
statements Method 1
Loop For condition
Statements
Next
Method 2
For condition Step update
Statements
Next
Example:
Method 1
Do…Loop While…Statement
Dim x As Integer
● first executes the statements and then
For x = 1 To 20
tests the condition after each execution
Print x
● always executed at least once
Next
Method 2
Dim x As Integer
For x = 1 To 20 Step 2
Print x;
Next
Control Arrays
● Option buttons are almost always grouped
in control arrays
● users can add or delete array elements at
run-time
● Elements of the array are referred to by
their name and index
● Two ways to create a control array:
● Create an individual control and
set desired properties. Copy the
control using the editor, then paste
it on the form.
● Create all the controls that to have
in the array. Assign the desired
control array name to the first
control. Then, try to name the
second control with the same
name.
Control ● It is important to note that an independent
● An object that can be drawn on a Form group of option buttons is defined by
object to enable or enhance user physical location within frames, not
interaction with an application according to a naming convention. That is,
● have properties that define aspects of a control array of option buttons does not
their appearance, such as position, size, work as an independent group just
and color, and aspects of their behavior, because it is a control array. It would only
such as their response to the user input work as a group if it were the only group of
● can respond to events initiated by the user option buttons within a frame or on the
or set off by the system form. So, remember physical location and
physical location only dictates the
Option Button independent operation of option button
● Aka radio buttons groups.
● allows the user to select from a set of Caption Title information at the top of frame
given choices
● allows the user to select from a set of Font Sets font type, style, size
given choices
● Are grouped (using frames) thus allowing Listbox
the user to choose only one among the ● presents a list of choices that are
available choices displayed vertically
Name allows the user to give a name to each of the ○ list is displayed in a vertical column
option buttons known as a list
○ A scroll bar appears if the list
Caption allows the user to display text to a specific option
button inside this control exceeds the
height of the list box
Value True - button is selected
False - not selected
● Syntax for Adding list:
controlname.AddItem list
● Syntax for Deleting an Item:
Checkbox
controlname.RemoveItem
● Gives choices to the user, although it is
controlname.ListIndex
different because checkboxes allow the
● Syntax for Deleting All Items:
user to choose as many choices as
controlname.Clear
presented in a checkbox
● For default selection:
Name allows the user to give a name to each of the controlname.ListIndex = Indexnumber
checkboxes
AddItem Used to add items inside the list box
Caption allows the user to display text to a specific
checkbox Appearance Selects a 3D or flat appearance
Value 0 - Unchecked or not selected Clear Removes all items from the list box
1 - Checked or selected
2 - Grayed Index Specifies the control array index
Combo Box
Image Control
● control presents a set of choices that are
● supports lesser methods than PictureBox
displayed vertically in a column
controls
● appearance of the control because the
● Loads picture faster, consumes less
combo box includes a text box on top of a
memory space and system resources
list box and only allows the selection of
● Cannot autosize to fit the picture to the
one item
sides of the borders, instead it stretches
● displays the list when its drop-down button
● Same syntax as Picture Box control
is clicked
● Syntax for Adding list:
Timer
controlname.AddItem list
● Not visible at run time
● Syntax for Deleting an Item:
● Uses only one event (timer event) that
controlname.RemoveItem
happens at a certain time interval
controlname.ListIndex
measured in milliseconds
● Syntax for Deleting All Items:
Name Name given to the control used in procedure
controlname.Clear
● For default selection: Enabled Set used to activate and deactivate events:
controlname.ListIndex = Indexnumber False - not executed
AddItem Used to add items inside the list box Interval Set the number to milliseconds, measures the time
for an action to be executed
Appearance Selects a 3D or flat appearance
Clear Removes all items from the list box Vertical and Horizontal Scrollbar
● enables the user to set its value to
Index Specifies the control array index
position a picture on an item at the desired
List returns/sets the items contained in a control’s location; either horizontally or vertically
list portion
Large return/set the max amount of change to
ListCount number of items inside the list box Change value property in a scroll bar when scrollbar
area is clicked
ListIndex number of the most recently selected item in
the list. If no item is selected, ListIndex = -1 Small return/set the min amount of change to
Change value property in a scroll bar when scrollbar
RemoveItem Used for removing or deleting an item area is clicked
Selected Set array with elements to True or False Max return/sets a scrollbar position’s max value
property setting
Sorted Sorts the list in ascending order
Min return/sets a scrollbar position’s min value
Style Specifies the style: standard or check box property setting
Statusbar
● Bar seen at the bottom of an application’s
window
● Used to display the status of the user’s
work and action inside the app
● Commonly used property:
Statussbar.panels(n)
Where n is the index of the panels