VB – Core III Functions Sub-routines Parameter passing Modules Scope Lifetime
Private Sub Command1_Click() Dim x, y As Double x = 1 y = 2 Debug.Print addUp(x, y) End Sub Private Function addUp(a as double, b As Double) addUp = a + b End Function User-defined functions x and y copied to a and b
Exercise – user-defined functions Write a function which calculates square root Use Newton's iteration – x approximates the square root of a hint – loop until abs(x*x-a)<1e-6
Subroutines = procedures Private Sub Command1_Click() Dim x As Double, y As Double x = 1 y = 200 Call bigger(x, y) End Sub Private Sub bigger(first As Double, second As Double) If first > second Then Debug.Print first Else Debug.Print second End If End Sub Functions return values Procedures do not – they just do something
Parameter passing – 2 methods Or parameters are passed by reference The addresses of the parameters are passed to the function Changing the parameter does affect the original Less memory and faster Dangerous – less modularity Use keyword ByRef in VB Parameters can be passed by value Copies of parameters are passed to the function (on a stack) Changing parameter in the function does not affect the original Uses extra memory – significant for large array And time for copy Default in VB – keyword ByVal
Parameter passing by reference Private Sub Command1_Click() Dim x As Double, y As Double x = 1 y = 200 Call swap(x, y) Debug.Print x, y End Sub Private Sub swap(ByRef first As Double, ByRef second As Double) Dim temp As Double temp = first first = second second = temp End Sub
Named arguments Private Sub Command1_Click() Dim x As Double, y As Double x = 1 y = 2 Debug.Print addUp(second:=x, first:=y) End Sub Private Function addUp(first As Double, second As Double) addUp = first End Function
Modules Separate files Contain VB functions, procedures and global variables Use for code and data which is needed in more than 1 form
Module example
Scope – public private dim Variables should be as local as possible scope of a variable : part of a program in which a variable can be referred to
Lifetime – how long a variable lasts DIM – local to a sub – execution of the sub Private/public in a form – while form is open Public in a module – while application runs Static – local to a sub – retains value
Modules and scope - exercise In a module, write a procedure which reverses the elements in an array The array should be public The array has 10 elements. The procedure should exchange elements 1 and 10, 2 and 9 and so on Call the procedure from a button on a form