Specifying Procedure Scope

The term scope means the areas in a program from which a particular program item — such as a variable, constant, user-defined data type, or procedure — is accessible, or "visible." Procedures in Visual Basic can have either private or public scope. A procedure with private scope is visible only to the other procedures in the module where it's declared; a procedure with public scope is visible to all procedures in every module in the workbook in which the procedure is declared, and in all workbooks that contain a reference to that workbook. If you don't specifically indicate otherwise, procedures have public scope.

If you want to limit the availability of a procedure to the module in which it's declared, use the Private keyword. Because procedures are public by default, you don't need to use the Public keyword to declare a public procedure; however, doing so makes it easier to see immediately which program elements have public scope and which ones have private scope. The following code declares two public procedures and one private procedure.


Public Sub CalcPayments()
    ' place statements here
    MsgBox "I'm public!"
End Sub

Sub CalcIncome()        ' Public by default
    ' place statements here
    MsgBox "I'm public, too!"
End Sub

Private Sub CalcSavings()
    ' place statements here
    MsgBox "I'm private!"
End Sub

Note

A procedure that's declared as Private cannot run as a stand-alone procedure. It can be called only from another procedure.

To limit the availability of a procedure to the workbook in which it's declared, declare the procedure itself as Public, but make the module private by adding the Option Private Module statement to the declarations section of the module.