SubProcedures in Visual Basic

Discussion in 'Visual Basic [VB]' started by Sanskruti, Mar 29, 2007.

  1. Sanskruti

    Sanskruti New Member

    Joined:
    Jan 7, 2007
    Messages:
    108
    Likes Received:
    18
    Trophy Points:
    0
    Occupation:
    Software Consultant
    Location:
    Mumbai, India
    There are two types of procedures: Sub procedures and functions.

    In Visual Basic, Sub procedures do not return values when they terminate, but functions do.If you declare variables in your new procedures, those variables might not be accessible from outside the procedure, and that fact is new also.

    A Sub procedure is a block of code that is executed in response to an event. By breaking the code in a module into Sub procedures, it becomes much easier to find or modify the code in your application.

    Procedures give you a way to break up your Visual Basic code, which is invaluable as that code grows longer and longer. Ideally, each procedure should handle one discrete task. That way, you break up your code by task; having one task per procedure makes it easier to keep in mind what each procedure does.You can place a set of Visual Basic statements in a procedure, and when that procedure is called, those statements will run.

    You can pass data to procedures for that code to work on and read that data in your code.

    Code:
    The syntax for a Sub procedure is:
    [Private|Public][Static]Sub procedurename (arguments)
    statements
    End Sub
    Example
    Code:
    Sub Main()
      Console.WriteLine("Hello there!")
      Console.WriteLine("Press Enter to continue...")
      Console.ReadLine()
    End Sub
    This Main Sub procedure is special because when a console application starts, Visual Basic calls Main automatically to start the program. When Main is called, the code will run as we want.

    You can also create your own Sub procedures, giving them your own names. Those names should give an indication of the procedure's task. For example, to show the "Hi there!" message, you might create a new Sub procedure named ShowMessage by simply typing this text into the code designer:
    Code:
     Sub Main()
    
     End Sub
     Sub ShowMessage()
    
     End Sub
    In the ShowMessage Sub procedure, you place the code you want to execute, like this code to display the message:

    Code:
    Module Module1
    
      Sub Main()
    
      End Sub
    
      Sub ShowMessage()
        Console.WriteLine("Hi there!")
      End Sub
    
    End Module
    If you want to, you can use a Visual Basic Call statement to call a Sub procedure like this: Call ShowMessage().

    This usage is still supported, although it goes back to the earliest days of Visual Basic, and there's no real reason to use it here.

    Note the parentheses at the end of the call to ShowMessage like this: ShowMessage(). You use those parentheses to pass data to a procedure.

    Passing Data to Procedures



    Say you want to pass the message text you want to display to the ShowMessage Sub procedure, allowing you to display whatever message you want. You can do that by passing a text string to ShowMessage, like this:

    Code:
    Module Module1
      Sub Main()
        ShowMessage("Hi there!")
        Console.WriteLine("Press Enter to continue...")
        Console.ReadLine()
      End Sub
      Sub ShowMessage()
    
      End Sub
    
    End Module
    A data item you pass to a procedure in parentheses this way is called an argument. Now in ShowMessage, you must declare the type of the argument passed to this procedure in the procedure's argument list:

    Code:
    Module Module1
    
      Sub Main()
        ShowMessage("Hi there!")
        Console.WriteLine("Press Enter to continue...")
        Console.ReadLine()
      End Sub
    
      Sub ShowMessage(ByVal Text As String)
    
      End Sub
    
    End Module
    This creates a new string variable, Text, which you'll be able to access in the procedure's code. The ByVal keyword here indicates that the data is being passed by value, which is the default in Visual Basic (you don't even have to type ByVal, just Text As String here, and Visual Basic will add ByVal automatically).

    Passing data by value means a copy of the data will be passed to the procedure. The other way of passing data is by reference, where you use the ByRef keyword. Passing by reference meant that the location of the data in memory will be passed to the procedure. Here's an important point to know: Because objects can become very large in Visual Basic, making a copy of an object and passing that copy can be very wasteful of memory, so objects are automatically passed by reference..

    Visual Basic automatically fills the Text variable you declared in the argument list in this example with the string data passed to the procedure. This means you can access that data as you would the data in any other variable.

    Passing Data to a Sub Procedure



    Code:
    Module Module1
      Sub Main()
        ShowMessage("Hi there!")
        Console.WriteLine("Press Enter to continue...")
        Console.ReadLine()
      End Sub
    
      Sub ShowMessage(ByVal Text As String)
        Console.WriteLine(Text)
      End Sub
    End Module
    And that's all you need! Now you're passing data to Sub procedures and retrieving that data in the procedure's code. You can pass more than one argument to procedures as long as you declare each argument in the procedure's argument list. For example, say you want to pass the string to show and the number of times to show it to ShowMessage; that code might look like this:

    Code:
    Module Module1
      Sub Main()
        ShowMessage("Hi there!", 3)
        Console.WriteLine("Press Enter to continue...")
        Console.ReadLine()
      End Sub
    
      Sub ShowMessage(ByVal Text As String, ByVal Times As Integer)
        For intLoopIndex As Integer = 1 To Times
          Console.WriteLine(Text)
        Next intLoopIndex
      End Sub
    End Module
    Here's the result of this code:
    Hi there!
    Hi there!
    Hi there!
    Press Enter to continue...

    Changing the value of arguments passed by reference is one way to pass data from a procedure back to the calling code, but it can be troublesome. You can easily change an argument's value unintentionally, for example. A more structured way of passing data back from procedures is to use functions .

    You should also know that an Exit Sub statement, if you use one, causes an immediate exit from a Sub procedure in case you want to leave before executing all code. For example, say you have a Sub procedure that displays reciprocals of numbers you pass to it, but you want to avoid trying to find the reciprocal of 0. You could display an error message and exit the procedure like this if 0 is passed to the procedure:

    Code:
    Sub Reciprocal(ByVal dblNumber As Double)
      If dblNumber = 0 Then
        Console.WriteLine("Cannot find the reciprocal of 0.")
        Console.WriteLine("Press Enter to continue...")
        Console.ReadLine()
        Exit Sub
      End If
      Console.WriteLine("The reciprocal is " & 1 / dblNumber)
      Console.WriteLine("Press Enter to continue...")
      Console.ReadLine()
    End Sub
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice