Second
Second
Unit - II 28
Visual Basic
Click on the “down arrow” to display the names of all the controls associated
with the form.
Event Box
This will list all the events recognized by visual basic for the controls or form
displayed in the object box. When we select an event , the event procedure associated
with that event name is displayed in the code window.
Split Bar
Use the split bar to view different parts of the code. Each part can be
independently scrolled at the same time.
Click on “Windows” on the menu bar. From the drop down menu select “Split”
this will split the code window into two horizontal panes.
Double click on the bar to close the pane or move the split bar to the bottom of
the code window.
Margin Indicator Bar
The gray area on the left side of the code window is the margin indicator.
Procedure View Icon
Displays the selected procedure. Only one procedure at a time is displayed in the
code window.
Full module view icon
Displays the entire code in the module
The Procedure Separator
It is a horizontal gray line that separates two procedures. It can be turned on or
off.
PROCEDURES
Anatomy of a Procedure
The Procedure is the piece of code that gets executed when the control that it is
associated with sense an event.
Unit - II 29
Visual Basic
A Procedure consists of all or Most of the following.
Name
Declaration Area
Statements
Terminator
Name
Every procedure must have a name. The name of a procedure is usually tied to
control. Example o procedure called cmd_click(). This means that this procedure will
be executed against the ‘Click’ event of the Cmdexit button.
Declaration Area
Declaration area is used to make all the declaration for variables, Constant, etc.
This makes it easy to locate variables and verify the same during the process od
debugging.
Declaration Area
The procedure deals with basic execution. A procedure will contain VBA
statements that will perform the intended task.
Call to other procedure (or) Functions
One way of reducing the number of lines in a procedure is to break up the entire
activity into smaller functions or procedures that can be called as and when required.
The principle used here is “Write once – Use many times”. A call to another procedure
or function is not a must for every procedure.
Terminator
Every procedure is terminated by the “End Sub” statement
Example :
Unit - II 30
Visual Basic
Sub Procedure
A Sub procedure is a series of Visual Basic statements enclosed by
the Sub and End Sub statements. The Sub procedure performs a task and then returns
control to the calling code, but it does not return a value to the calling code.
Each time the procedure is called, its statements are executed, starting with the
first executable statement after the Sub statement and ending with the first End
Sub, Exit Sub, or Return statement encountered.
Syntax
Example
Sub Operator (ByVal task As String)
Dim stamp As Date
stamp = TimeOfDay()
MsgBox("Starting " & task & " at " & CStr(stamp))
End Sub
Function Procedure
A Function procedure is a series of Visual Basic statements enclosed by
the Function and End Function statements.
The Function procedure performs a task and then returns control to the calling
code. When it returns control, it also returns a value to the calling code.
Each time the procedure is called, its statements run, starting with the first
executable statement after the Function statement and ending with the first End
Function, Exit Function, or Return statement encountered.
We can define a Function procedure in a module, class, or structure. It
is Public by default, which means we can call it from anywhere in VB application
that has access to the module, class, or structure.
A Function procedure can take arguments, such as constants, variables, or
expressions, which are passed to it by the calling code.
Unit - II 31
Visual Basic
Syntax
Example
Function sum (int1 as integer , int2 as integer ) as integer
Sum = int1 + int2
End function
The function ‘sum’ can be called anywhere in the program. It can be called by
simply passing the variables to it as argument.
CONTROL STRUCTURES
Control structures are used to control the flow of program’s execution. Visual
Basic supports control structure such as
If….Then
If….Then….Else
Select…..Case
For…..Next
Do [{While | Until} Condition]…..Loop
While…..Loop
If….Then Statement
The If...Then selection structure performs an indicated action only when the
condition is True; otherwise the action is skipped.
Syntax
If <condition> Then
statement
End If
Unit - II 32
Visual Basic
Example
If average>75 Then
Text1.Text = "A"
End If
If….Then…..Else Statement
The statement is executed only if the condition is True, the statement1 is
executed, otherwise the Else part is executed.
Syntax
Example
Unit - II 33
Visual Basic
Syntax
Select Case testexpression
[Case Expressionlist – n
[Statements-n]]…
[Case Else
[Elsestatements]]
End Select
Example
Looping Statement
For…..Next Statement
This statement is used to execute a statement or a block of statement a certain
number of times.
Unit - II 34
Visual Basic
Syntax
For counter [ As datatype ] = start To end [ Step ]
[ statements - 1 ]
----------
----------
[statements – n]
Next [ counter ]
Example
For I = 1 to 10
Total = total + I
Next I
How does it works
The For statement initializes the value of I as 1. Since 1 is less than 10, the next
statement is executed.
The statement Total = Total + I is executed
The statement Next I increments the value of I by 1.
The control shifts to the beginning of the loop, where the value of I is checked.
If the value of I is more than 10, the loop terminates,.
Syntax
Do [ {While | Until } Condition ]
[Statements]
[Exit Do]
Loop
Example
I =1
Do While I < 10
Sum = sum + I
I=I+1
Loop
Unit - II 35
Visual Basic
How does it works
The value of I is initialized to 1.
The exit condition is first checked to see of I is less than 10. if I is less than 10,
then the statements in the loop are executed.
Sum = Sum + 1 and I = I + 1 are executed
The keyword Loop returns the controls to the Do While …. Statement , where
the exit condition is checked.
Syntax
While condition
[statements]
Wend
Example
Dim I as Integer
I =1
While I < 10
I = sum + 1
I = I+1
Wend
Unit - II 36
Visual Basic
Syntax
Do
Statement – 1
----------------
---------------
Statement – n
Loop While condition
Example
Counter = 200
Do
Text1.text = str (counter)
Counter = counter + 1
Loop While counter < 501
FILES
File System Controls
There are three File System Controls in Visual Basic
Drive List Box ( Moving from one drive to another)
Dir ListBox ( Moving from one directory to another)
File List Box ( List files in a directory)
Unit - II 37
Visual Basic
Phase – I
Open a form and create the following controls on it
The DriveListBox
The DirListBox
The FileListBox
Unit - II 38
Visual Basic
2 ChDir Changes the default directory
3 MkDir Creates a new directory
4 RmDir Deletes a directory
5 Name Renames a files
6 Kill Deletes a file
7 FileCopy Copies source file to destination
8 FileDateTime Returns the date & time when the file was modified
9 GetAttr Returns the attributes of file as an integer value
10 SetAttr Sets the attributes of a file
Unit - II 39
Visual Basic
Example
Name Oldfile as Newfile
Old file is renamed as newfile
Kill : Deletes a file or files
Syntax
Kill Pathname
Example
Kill “textdoc” ‘ To delete the file ‘textdoc’
Kill “*.Doc” ‘ To delete all the “*.Doc” files in the current directory
FileCopy : Copies the source file to the specified destination
Syntax
FileCopy Source , Destination
Example
FileCopy Maxfile Highfile
This will copy the contents of the Maxfile to Highfile
FileDateTime : Returns the date & time when the file was modified
Syntax
FileDateTime (Pathname)
Example
Dated = FileDateTime (“Maxfile”)
This will return the date and time when the file ‘Maxfile’ was last modified.
GetAttr : Returns the attributes of a file as an integer value
Syntax
GetAttr (Pathname)
Example
Dim Fileattrib as Integer
Fileattrib = GetAttr (Maxfile)
SetAttr : Sets the attributes of a file
Syntax
Setattr Pathname , attributes
Example
Setattr Highfile , Vbhidden + Vbsystem
This will set the attributes of the file as Hidden and System
Unit - II 40
Visual Basic
Types of Files
From the programming point of view files are classified as
Sequential Access files
Random Access files
Binary Access Files
Syntax
Open Pathname for Input As [ # ] filenumber
Example
C:\Svm\Master.txt for Input As #1
Unit - II 41
Visual Basic
Closing a File
A file must be closed for the operating system to write the data from the
associated buffer to the file.
Syntax
Close [ FileNumber List ]
Example
Close #1
Reading a File
The Read operation transfer the contents of the file from the disk to the buffer.
The Input function provided by visual basic reads a sequential files contents into the
buffer.
The Input functions has three options
Input
Input#
Line Input #
Unit - II 42
Visual Basic
1. Input
Syntax
Input ( number , [#] filenumber )
Input is the command name
Number is the number of character to read
Filenumber is the number of the open file that has to be read.
Example
String1 = Input ( 25 , #1)
2. Input #
Syntax
Input #filenumber , varlist
Filenumber is the file number of the file to be read
Varlist is the list of variable that will hold the data
Example
Input #1 , serialNum , Name , Designation
3. Line Input #
Syntax
Line Input #filenumber , databuffer
Line means read the entire line
Filenumber is the number of the file to be read
Databuffer is the variable that will hold the line that has been
read.
Example
Line Input #1 , linebuffer
Writing a File
We have finished with opening , closing and reading a sequential file , let us take
a look at writing to a file.
Before we write to the file , we need to decide if we want to
Creates a file if does not already exists
Overwrites the existing contents if the file is opened in ‘Output’
mode.
Appends new data if the file is opened in ‘Append’ mode.
Syntax 1:
Open Pathname for Append as #1
Unit - II 43
Visual Basic
Open is the command to open the file
Pathname is the filename of the file
Append is the keyword to open the file in append mode
#1 is the filenumber of the file to be written into.
Syntax 2:
Print #filenumber , Outputlist
Print is the command to write the data to the file
Filenumber is the number of the file that has to be written
Output consists of the data to be written , and argument to
position the data correctly.
Example
Open c:\Svm\Stud.dat for Random As #1 len = 45
Closing a File
A file must be closed for the operating system to write the data from the
associated buffer to the file.
Syntax
Close [ FileNumber List ]
Example
Close #1
Reading a File
Read a record from the file we use the “Get” Command
Unit - II 44
Visual Basic
Syntax
Get [#] filenumber , [ recordnumber] , variable name
Syntax
Put [#] filenumber , [recnumber] , varname
Put is the command
Filenumber is the file number has been opened for writing
Recnumber where the writing begins
Varname is the variable that contains data to be written to the disk.
Example
Put #1 , 12 , myrecord
Unit - II 45
Visual Basic
FileMode is the mode to open the file
Len is the length of the record.
Example
Open c:\Svm\Stud.dat for Binary As #1 len = 45
Closing a File
A file must be closed for the operating system to write the data from the
associated buffer to the file.
Syntax
Close [ FileNumber List ]
Example
Close #1
Example
Put #intMyFile, , strData
Unit - II 46
Visual Basic
File System Object Model
The File System Object model provides an object – based tool for working
with folders and files. Using the object. method the user can create , alter , move ,
and delete folders, detect if particular folder exist , and if so , where.
This creates an instances of the object as FileSystemObject. The object will be referred
to as ‘fil’.
2. Use the Create Object method to create a File System Object
Set fil = CreateObject (“Scripting.FileSystemObject”)
Unit - II 47
Visual Basic
Step3: Access the Object’s Properties
Once we have a handle to an object , we can access its properties.
Set fldr = fileobj.GetFolder (“c:\”)
Debug.Print “Folder name is “ , fldr.Name
2. The OpenTextFile method of the FileSystemObject with the writing flag set
Dim fileobj As New FileSystemObject , fil As file , nts as New textstream
Set nts = fileobj.openTextFile (“C:\test.txt”, ForWriting)
Unit - II 48
Visual Basic
Private Sub Command2_Click()
Dim fileobj , txtfile , filename As string
Set fileobj = CreateObject (“Scripting.FileSystemObject”)
Filename = Text2.Text
Set txtfile = fileobj.CreateTextFile (“C:\” & filename , True)
Txtfile.Write s
Txtfile.WriteBlanklines (3)
Txtfile.Close
End Sub
Task Method
Move a File File.Move or FileSystemObject.MoveFile
Copy a file File.Copy or FileSystemObject.CopyFile
Delete a file File.Delete or FileSystemObject.DeleteFIle
MENUS
Menus contains a number of options, logically organized and easily accessible
by the user.
Windows – based applications follow the standard of a File menu on the left ,
then optional menus a such as Edit , and Tools, followed by Help on the right.
When the user clicks a menu option, a list of option is displayed. Clicking on any
item on the list will generate a click event.
Visual Basic provides a very simple methods to create menus for VB applications.
We can create menus using the Menu Editor.
Unit - II 49
Visual Basic
A menu editor can be added only after opening a project.
Menu editor command is chosen from the Tool menu or the menu editor button
is clicked in the Tool Bar.
Unit - II 50
Visual Basic
13. Help Context ID: Allows to assign a unique numeric value for the Context ID. This
value is used to find the appropriate help topic in the help file identified by the Help
file property.
14. Negotiate Position : This property determine whether and how the menu appears
in the container form.
15. Next : Moves selection to the next line
16. Insert : Inserts a line in the list box above the currently selected line
17. Delete : Deletes the currently selected line
18. OK : Closes the menu editor and applies all changes to the last form we selected
19. Cancel : Closes the Menu Editor and cancels all changes.
Now Double click on the ToolBar Control. A long flat button will appear on the form
below the menu bar.
Unit - II 51
Visual Basic
There are three options.
General
Buttons
Picture
General
Using this options we can set the mouse pointer type, adjust the size of the
buttons, and set other parameters.
Buttons
In this option , we can insert the buttons , set the control keys for the button
provide the ToolTip text , etc.
Picture
View the picture of the icon selected.
Unit - II 52
Visual Basic
Insert or add the images to the image list. Click the image button. Select the icon
we want. The selected icon will be displayed in the Image list
Color
We can modify the color we can choose.
Unit - II 53
Visual Basic