Public and Private Procedures
When you make a complex program, the easiest way to handle is to decompose a big program into smaller components. These components are called procedures .
There are several types of procedures used in Visual Basic:
1. Sub procedures do not return a value.
2. Function procedures return a value.
3. Property procedures can return and assign values, and set references to objects.
We suspend the discussion about Property until we discuss about OOP . In this lesson we only discuss Sub procedures and Function procedure.
There are two common attributes can be attached to a procedure (Sub or Function):
Procedures are by default Public in all modules, which means they can be called from anywhere in the application. The default means if you do not specify the attribute, VB will automatically assume the procedure has Public attribute. Private attribute indicates that the procedure is accessible only to other procedures within the module where it is declared. The following simple project is designed to make you understand the difference beween private and public procedure.
Project: Public and Private Procedure
1. Make a new Standard Exe project
2. Add textbox into the form. Change the text property of the textbox into any number.
3. Type the following code into the form
Private Sub Form_Click()
Dim X As Integer
X = Val(Text1.Text)
MsgBox "Result = " & X
4. Add a standard module into the form. Type the following code into the standard module
Private myModuleVar As Integer
Private Function myPrivateFunction(myFirstArgument As Integer, _
mySecondArgument As Integer) As Integer
myPrivateFunction = myFirstArgument + mySecondArgument
Public Sub myPublicSubProcedure(ByRef myArgument As Integer)
Dim myLocalVar As Integer
myLocalVar = 39
myModuleVar = 10
myArgument = myPrivateFunction(myLocalVar, myModuleVar)
5. Run the program and trace the value of each variables