Date post: | 03-Jun-2018 |
Category: |
Documents |
Upload: | sgshekar30 |
View: | 216 times |
Download: | 0 times |
of 41
8/12/2019 17.vb_5
1/41
CSI 1306
PROGRAMMING IN VISUAL BASIC
PART 5
8/12/2019 17.vb_5
2/41
Part 5
1. Procedures
2. Sub Procedures
3. Function Procedures
8/12/2019 17.vb_5
3/41
Procedures
A procedure is a block of VB code entered in a
VB module that is executed (run) as a unit
Many procedures can be entered in a singlemodule
Many modules can be added to a single workbook
To add a new module to a workbook, select Module
from the Insert menu
8/12/2019 17.vb_5
4/41
8/12/2019 17.vb_5
5/41
Procedures
When we subdivide a problem, translating the
solution into Visual Basic code involves
Translating the algorithm for each smaller problem into
a Visual Basic procedure
Developing a main procedure (with actual parameters)
that assembles the other procedures (with formal
parameters) as appropriate
8/12/2019 17.vb_5
6/41
Procedures
This technique is known as structuredprogramming. It
is characterized as
Modular(each procedure dedicated to one task which is
of limited and manageable size)
Has a Main-line procedure that controls program flow
by branching to the various sub-problem procedures
Single entryto, and single exitfrom, each procedure
GoTo-less code (not using the GoTo statement avoids
spaghetti code)
8/12/2019 17.vb_5
7/41
Procedures
As we will see
We can debug each procedure independently, a much
simpler process than trying to debug a complexprogram as a whole
The procedures are reusable. We can combine a
procedure, as appropriate, with other procedures to
solve other problems
8/12/2019 17.vb_5
8/41
Procedures
To call a procedure means to run (execute) it
When one procedure calls a second
The first procedure is the calling procedure; the second
procedure is the called procedure
VB first looks for the called procedure in the modulecontaining the calling procedure
if not found, it looks in all the other modules in the
workbookThere are two types of procedures
SUB procedures
FUNCTION procedures
8/12/2019 17.vb_5
9/41
2. Sub Procedures
8/12/2019 17.vb_5
10/41
Sub Procedures
A sub procedure performs a series of operationsand actions but does not return a value to thecalling procedure
Sub Name (arguments)CODE
End Sub
A sub procedure without arguments can be run onits own or be called by another procedure For example, it can be run from a worksheet by
selecting Macro from the Tools menu (Tools >> Macro>> Macros)
A sub procedure without arguments is known as a macro
8/12/2019 17.vb_5
11/41
Sub Procedures
A sub procedure with arguments can only executewhen it is called by another procedure
Arguments are declared the same way as variables, butwithout the word Dim
If there is more than one argument, they are separatedby commas
The calling procedure passes values for the argumentsto the called procedure
Sub Name (X as Integer, Y as String, Z as Single)CODE
End Sub
8/12/2019 17.vb_5
12/41
Sub Procedures
To call a sub procedure without arguments, useeither
Call Name
To call a sub procedure with arguments, use either
Call Name (Argument1, Argument2,.)
ie. Call FindMax (X, Y, Z)
8/12/2019 17.vb_5
13/41
Sub Procedures
If you call a procedure that has arguments, as we
saw with algorithms,
The values of the arguments in the calling procedure
(the actual parameters) are passed to the arguments in
the called procedure (the formal parameters)
The arguments in the calling procedure may be
Constants, expressions or variables
8/12/2019 17.vb_5
14/41
Sub Procedures
Sub Main()
'The calling procedure. Will show up on Tools Macro
Dim X as Integer
Dim Y as Single
Dim Z as Boolean
Call One (X, Y, Z) 'OK
Call One (X, Y) 'Not OK what about Z?
Call One (Y, Z, X) 'Not OK order is Int, Single, Boolean!
End Sub
Sub One (A as Integer, B as Single, C as Boolean)
'The called procedure. Will not show on the Tools menu
CODE
End Sub
8/12/2019 17.vb_5
15/41
Sub Procedures
When the arguments in the calling procedure arevariables, the called procedure can change thevalueof these variables (passing by reference or
two-way passing), using the word ByRef If you want to avoid the possibility of the called
procedure changing the value of variables in thecalling procedure, preface the arguments in the
called procedure with the word ByVal(passingby value or one-way passing)
In either case, the number and type of argumentsin the calling statement must agree with those in
the called procedure
8/12/2019 17.vb_5
16/41
8/12/2019 17.vb_5
17/41
Sub Procedures
Sub Main ()
Dim X as Integer
Dim Y as Single
X = 3
Y = 3.1
Call One (X, Y)
MsgBox (X = & X & Y = & Y)
End Sub
Sub One (ByRef A as Integer, ByVal B as Single)A = 9
B = 2.1
End Sub
Main One
X Y A B
3
3 3.1
33.1
9 3.1
9 2.1
9 3.1
Example 1
8/12/2019 17.vb_5
18/41
Sub Procedures
Observe that we are not concerned about thepossibility of identical names for variables orarguments in the calling and called procedures
Since they are in separate procedures, even if a variableor argument name is identical in the two procedures,each is evaluated independently by Visual Basic (ie. asif they bear no relationship to one another)
This is why our procedure code is portable andreusable
However, we often want the called procedure toreturn a value
8/12/2019 17.vb_5
19/41
3. Function Procedures
8/12/2019 17.vb_5
20/41
Function Procedures
A function procedure performs a series ofoperations and returns a single valueFunction Name (arguments) as Type
CODEName = Expression
End Function
Observe that a function procedure will always
contain an assignment statement that assigns avalue to a variable with the name of the function
The type of that variable is defined in the functionheader line (as Type)
8/12/2019 17.vb_5
21/41
Function Procedures
A function procedure is never run by itself. It is either
called from within another procedure or from a formula in
a worksheet cell
To call a function procedure from within another
procedure, use the function in an assignment statement
variable = Name(arguments)
For example, cells(6, 8) = Profit (us,pc,sp) calls the procedure
Function Profit(ByVal UnitsSold As Integer, ByVal ProdCost As Single, _
ByVal SalePrice As Single) As Single
Profit = UnitsSold * (SalePrice - ProdCost)
End Function
8/12/2019 17.vb_5
22/41
Function Procedures
Z = Name (X, Y) a statement in the calling procedure
FunctionName (ByRef A as Integer, ByVal X as Single) as Integer
Name = ????
End Function
The variable X, an argument in the callingprocedure, is a different variable than the variableX, an argument in the called procedure
8/12/2019 17.vb_5
23/41
Function Procedures
Sub Main ()
Dim X as Integer
Dim Y as Single
Dim Z as Boolean
X = 1
Y= 1.2
Z = Compare (X, Y)
MsgBox (X & Y & Z)
End Sub
Function Compare (ByRef A as Integer, ByVal B as Single) as Boolean
If (A > B) Then
Compare = True
ElseCompare = False
End If
A = 3
B = 2.4
End Function
Main CompareX Y Z || A B Compare1 1.2 ||
|| 1|| 1.2|| F|| 3
|| 2.43 1.2 F ||
Example 2
8/12/2019 17.vb_5
24/41
Function Procedures
a function procedure can be entered in a worksheetcell as a formula ie. called from a worksheet The function procedure is then known as a user defined
function It must be entered in a module code window
If it is entered in a worksheet code window (right click sheettab and select View code), it cannot be called from a worksheet
If the formula in cell A1 is =Compare(B1,C1)
Cell A1 would contain a True if the value in B1 isgreater than the value in C1. Otherwise, cell A1 wouldcontain False
8/12/2019 17.vb_5
25/41
Translate 19 see 17.vb_5.xls
Translate algorithm 5.1 into Visual Basic using theworksheet CSI1234
Name is in column A
Midterm mark is in column B Final exam mark is in column C
Final mark is in column D
Data starts in row 3
The algorithm is to find the number of studentswith a final mark greater than the average finalmark
8/12/2019 17.vb_5
26/41
Algorithm 5.1
Putting it all together
Name: AVGLGivens :L, N
Change: NoneResult : AvgIntermediates: Sum, I
DefinitionAvg := AVGL(L, N)
Get L, N
Let Sum = 0
Let I = 1
Loop When (I
8/12/2019 17.vb_5
27/41
Algorithm 5.1
Our algorithms AVGL & COUNTL process data
in a list L of length N.
Lets rewrite them to process data in a list on a
worksheet (WS) starting at a particular row (Row)
of column (Col) and ending at the first blank cell
in that column.
8/12/2019 17.vb_5
28/41
Algorithm 5.1
Name: AVGLGivens: L, N
Change: NoneResults: AvgIntermediates: Sum, IDefinitionAvg := AVGL(L, N)
Get L, N
Let Sum = 0
Let I = 1
Loop When (I
8/12/2019 17.vb_5
29/41
Algorithm 5.1
Now, lets translate the algorithm into a Visual
Basic function procedure so that it can be called
from another procedure or from a formula in a
worksheet.
8/12/2019 17.vb_5
30/41
Algorithm 5.1
Name: AVGLGivens: Row, Col
Change: NoneResults : AvgIntermediates: Sum, Count, ValueDefinitionAvg := AVGL(Row, Col)
Get Row, Col
Let Sum = 0
Let Count = 0
Loop until empty cell
Get Value(Row,Col)Let Sum = Sum + Value
Let Count = Count + 1
Let Row = Row + 1
Finish Loop
Let Avg = Sum/Count
Give Avg
Function AVGL(ByVal Row As Integer, _ByVal Col as Integer) As Single
Dim Sum as Single
Dim Value as Single
Dim Count as Integer
Dim Avg as Single
Sum = 0Count = 0
Do Until (IsEmpty(Cells(Row, Col)))
Value = Cells(Row, Col)
Sum = Sum + Value
Count = Count + 1
Row = Row + 1Loop
Avg = Sum/Count
AVGL = Avg
End Function
8/12/2019 17.vb_5
31/41
Algorithm 5.1
Applying the same process to COUNTL produces
the following function procedure.
8/12/2019 17.vb_5
32/41
Algorithm 5.1
Name: COUNTLGivens: Col, Row, V, Value
Change: NoneResult: CountIntermediate:DefinitionCount := COUNTL(Row, Col, V)
Get Row, Col, V
Let Count = 0
Loop until empty cell
Get Value(Row,Col)If (Value > V)
Let Count = Count + 1
Row = Row + 1
Finish Loop
Give Count
Function CountL(ByVal Row As Integer,ByVal Col As Integer, ByVal V AsSingle) As Integer
Dim Value As Single
Dim Count As Integer
Count = 0
Do Until IsEmpty(Cells(Row, Col))
Value = Cells(Row, Col)
If (Value > V) Then
Count = Count + 1End If
Row = Row + 1
Loop
CountL = Count
End Function
8/12/2019 17.vb_5
33/41
Name: MAINGivens: Marks, NStu
Change: NoneResults: NGoodIntermediate: AMarkDefinitionNGood:=MAIN(Marks,Nstu)
Get Marks, NStu
AMark := AVGL(Marks,NStu)NGood := COUNTL(Marks,NStu, AMark)
Give NGood
Sub Main()
Dim Col as Integer
Dim Row As Integer
Dim Ngood as Integer
Dim AMark as Single
Worksheets(CSI1234).Activate
Row = 3
Col = 4
Amark = AVGL(Row, Col)
Ngood = COUNTL(Row, Col, Amark)MsgBox(Ngood & >Avg)
End Sub
Algorithm 5.1
Name: MAINGivens: Row, Col, WS
Change: NoneResults: NGoodIntermediate: AMarkDefinitionNGood:=MAIN(Row, Col, WS)
Go to Worksheet WS
AMark := AVGL(Row, Col)
NGood := COUNTL(Row, Col, AMark)
Give NGood
8/12/2019 17.vb_5
34/41
Algorithm 5.1
Function AVGL(ByVal Row _
As Integer, ByVal Col As _
Integer) As Single
Dim Sum As Single
Dim Value As Single
Dim Count As IntegerSum = 0
Count = 0
Do Until IsEmpty(Cells(Row, _
Col))
Value = Cells(Row, Col)
Sum = Sum + Value
Count = Count + 1
Row = Row + 1
Loop
AvgL = Sum / Count
End Function
Function COUNTL(ByVal _
Row As Integer, ByVal Col As _
Integer, ByVal V As Single) As _
Integer
Dim Value As Single
Dim Count As Integer
Count = 0
Do Until IsEmpty(Cells(Row, _
Col))
Value = Cells(Row, Col)
If (Value > V) Then
Count = Count + 1
End IfRow = Row + 1
Loop
CountL = Count
End Function
Sub Main()
Dim Col as Integer
Dim Row As Integer
Dim Ngood as Integer
Dim AMark as Single
Worksheets("CSI1234").Activate
Row = 3
Col = 4
Amark = AVGL(Row, Col)
NGood = COUNTL(Row, _Col, Amark)
MsgBox(Ngood & ">Avg")
End Sub
8/12/2019 17.vb_5
35/41
Translate 20 see 17.vb_5.xls
Use algorithm 5.4 to find how many ties there
were for the maximum grade in CSI1234
Name is in column A
Midterm mark is in column B
Final exam mark is in column C
Final mark is in column D
Data starts in row 3 and ends in row 20
8/12/2019 17.vb_5
36/41
8/12/2019 17.vb_5
37/41
CMAX
(01) Get L, N
(02) Max := MAXL(L,N)
(03) Nmax :=
SEARCHK(L,N,Max)
(04) Give NMax
MAXL(11) Get L, N(12) Max = -1(13) I = 1(14) Loop When (I Max)
(16) Max = LI
(17) I = I + 1(18) Finish Loop(19) Give Max
COUNTk(21) Get L, N, K(22) C = 0
(23) I = 1(24) Loop When (I Max) Then
Max = Value
End If
Next Row
End Sub
8/12/2019 17.vb_5
38/41
CMAX
(01) Get L, N
(02) Max := MAXL(L,N)
(03) Nmax :=
SEARCHK(L,N,Max)
(04) Give NMax
MAXL(11) Get L, N(12) Max = -1(13) I = 1(14) Loop When (I Max)
(16) Max = LI
(17) I = I + 1(18) Finish Loop(19) Give Max
COUNTk(21) Get L, N, K(22) C = 0
(23) I = 1(24) Loop When (I
8/12/2019 17.vb_5
39/41
Homework
8/12/2019 17.vb_5
40/41
When and where do you use each of the following?
Dim x As Integer
ByRef x As Integer
ByVal x As Integer
8/12/2019 17.vb_5
41/41
Write a sub procedure that takes one parameter and producesa message box that says The argument sent to me was: and then displays the value of the parameter. Now write asub procedure that calls this procedure.
Create a function procedure that uses several arguments andreturns a value based on a calculation. Write a sub
procedure that calls this function procedure.
Write a sub procedure that consists entirely of calls to otherprocedures. Use at least three procedure calls, onefunction procedure, one sub procedure and one requiringarguments. Now write the procedures that it calls.