VISUAL BASIC TIP

Code VBTPFUN002

Description

USING PROCEDURE-LEVEL VARIABLE ACROSS THE PROCEDURES.

VB Version Compatibility

This solution works in VB4,VB5,VB6 & VBA (Visual Basic For Application).

THEORY

If you want to  exchange information between Procedures in a particular Module then one or the way of doing it that you need to declare a Module-Level variable. A Module-Level variable is available  within the module to all the procedures. But there are certain drawback using Module-Level variable like You do not know which procedure changes it value and another important factor is memory Module-Level variable  has the same life as the Module and consume memory till Module is loaded in memory. To avoid using Module-Level variable  you can declare Procedure-Level variables and exchange information between procedures using ByRef way of passing Arguments.

Passing Arguments using ByRef keyword  gives the procedure access to the actual variable contents in the memory address location. Due to this a variable's value can be changed by the procedure it passed in. It is the default way of passing Argument and you do not have to specify ByRef Keyword.

TIP
  1. Start a new visual basic project.
  2. Add a FORM , if not added automatically.
  3. Add following procedure in FORM.
    Private Sub BreakName(ByVal FullName, ByRef FirstName, ByRef LastName)
        Dim I As Integer
        Dim L As Integer
        L = Len(FullName)
        I = InStr(1, FullName, " ")
        FirstName = Left(FullName, I - 1)
        LastName = Mid(FullName, I + 1, L - I)
    End Sub
  4. Add following code in Load() Event of FORM.
Private Sub Form_load()
   Dim FName As String
   Dim LName As String
   BreakName "BILL GATES", FName, LName
   MsgBox FName
   MsgBox LName
End Sub
  1. Save and run the project. you will see first Message Box will be prompted with "BILL" and next MessageBox will be prompted with "GATES".

--------------------X-X-X-X-X-X-X-X--------------------

SPECIAL NOTE :- This tip is tested thoroughly. Use this tip is your own risk. Visual Code is not responsible for any damage caused directly or indirectly.

BACK

1