Subroutines in VBScript

Discussion in 'Visual Basic [VB]' started by Sanskruti, May 1, 2007.

  1. Sanskruti

    Sanskruti New Member

    Joined:
    Jan 7, 2007
    Messages:
    108
    Likes Received:
    18
    Trophy Points:
    0
    Occupation:
    Software Consultant
    Location:
    Mumbai, India

    Introduction



    A subroutine is a container that holds a series of VBScript statements. Suppose you'd like to create a block of code that accomplishes some specific task. Maybe you need to accomplish that task in various places throughout your code. All you need to do is create, or declare, the subroutine in your script. Once you've declared the subroutine, you can call it anywhere within your code. When your program calls a subroutine, the flow of the code is temporarily diverted to the statements within the subroutine.

    Once the subroutine has finished executing, control returns to the code that called the subroutine and execution picks up from there. A subroutine is a block of code that can be called from anywhere in a program to accomplish a specific task. Subroutines can accept starting data through subroutine declaration variables called parameters. However, subroutines do not automatically return a result code or an argument to the caller.

    You declare subroutines using the Sub keyword and end them using the End Sub statement.

    The structure of a subroutine is

    Code:
    Sub Subroutine_Name(argument1, argument2, ..., argumentn)
       ...code within the subroutine
    End Sub
    where Subroutine_Name is the name of the subroutine and argument1 through argumentn are optional arguments, often called parameters, that you can pass to the subroutine. If you choose not to pass any arguments to the subroutine, the parentheses are optional, as you will see in a moment. An argument or a parameter is a variable that a procedure requires in order to execute. In VBScript, arguments must be supplied in the order specified by the procedure. The name of a subroutine should adequately describe what the subroutine is for. You must name subroutines using the same rules as variables; letters and numbers are fine as long as the first character is not a number, and you cannot use symbols. If you enter an invalid name for a subroutine, the VBScript run-time interpreter will alert you of the problem when you attempt to try your script.

    The following are some valid subroutine names:
    • WelcomeTheUser
    • PrintInvoice
    • Meters2Yards
    The following are some unacceptable subroutine names:
    • User.Welcome
    • 2Printer
    • Miles*1.609
    If you want, a subroutine can require that the code statement that calls that subroutine provide one or more arguments or variables that the subroutine can work with. Any time you need preexisting data to perform the task within the subroutine, arguments are very helpful. For example, the following subroutine accepts an argument to be used in the subroutine as a message to be displayed to the user:

    Code:
    Sub ShowMessage(CurrentMessage)
       MsgBox CurrentMessage, vbOkOnly, "Important Message"
    End Sub
    In this case, CurrentMessage is the argument, and it is treated like any other variable in the subroutine. It is treated exactly as if it had been declared with a Dim statement with one very important difference. The CurrentMessage argument variable starts out pre-initialized with a value that was supplied by the code that called this subroutine. When you declare a procedure and specify that it will receive arguments, you can specify how it interacts with those argument variables. You can either give the subroutine a copy of a value supplied as an argument, or you can refer it to the actual variable that the caller is using. If you give the subroutine a copy of the variable, the subroutine can then make changes to its own copy without changing the original.

    Often, a subroutine might not require any arguments, and you can drop the parentheses. Suppose you have a subroutine that simply displays information to the user. In that case, the subroutine doesn't need any arguments, as in the following case:

    Code:
    Sub ShowAboutMessage
       MsgBox "This Web page was designed by the WebWizard."
    End Sub 
    In this case, you can see that the code lists no arguments, so it does not require the parentheses. On the other hand, if you declared a procedure using one or more arguments, you'd use the parentheses:

    Code:
    Sub ShowAboutMessage(Message)
       MsgBox Message
    End Sub 

    Calling a Subroutine



    Now that you've learned how to create a subroutine, how do you call one? You can call a subroutine throughout the rest of the application once you've declared and created it. You can call subroutines by using the Call keyword or just entering the name of the subroutine on a line of code. For example, to call a subroutine called ShowMessage, you could enter

    Code:
    ShowMessage "This is the message." 
    You could also use the Call keyword and enter

    Code:
    Call ShowMessage("This is the message.") 
    Notice that in the first method, you do not place parentheses around the arguments of the subroutine. On the other hand, if you use Call, you must enclose the arguments in parentheses. This is simply a convention that VBScript requires. What if a subroutine has no arguments? To call the subroutine ShowAboutMessage, you could enter

    Code:
    ShowAboutMessage 
    or 
    Call ShowAboutMessage() 
    or you could use 
    Call ShowAboutMessage
    The first method simply lists the name of the subroutine. The second method uses Call but doesn't require parentheses because the subroutine has no arguments. Whether you use the parentheses when you call or declare a subroutine with no arguments is a personal preference about writing code. When you call a subroutine without the Call statement, it can be more difficult to figure out the difference between a subroutine and a variable in your code, especially if your code is lengthy. Although the choice is up to you, it is generally recommended that you always use the Call statement when calling subroutines for the sake of readability.

    Exiting a Subroutine



    The code within your subroutine will execute until one of two things happens. First, the subroutine might get down to the last line, the End Sub line, which terminates the subroutine and passes the baton back to the caller. This statement can appear only once at the end of the subroutine declaration. The second possibility is that VBScript could execute the following code statement:

    Code:
    Exit Sub 
    when placed inside the subroutine. You might use this statement if you need to provide more than one exit point for the subroutine. However, you shouldn't need to use this very often if your subroutine is constructed properly. Consider the following subroutine:

    Code:
    Sub ConvertFeetToInches
       Feet = InputBox("How many feet are there?")
       If Feet < 0 Then
          Exit Sub
       Else
          MsgBox "This equals " & Feet * 12 & " inches."
       End If
    End Sub 
    This subroutine contains an Exit Sub statement, which could be avoided by changing the subroutine to

    Code:
    Sub ConvertFeetToInches
       Feet = InputBox "How many feet are there?")
       If Feet >= 0 Then
          MsgBox "This equals " & Feet * 12 & " inches."
       End If
    End Sub 
    Here, the If…Then conditional structure was rewritten to avoid the need for the Exit Sub statement. In this case, the subroutine could be changed to avoid Exit Sub. Keep in mind, however, that you may occasionally need to use Exit Sub to exit a subroutine, particularly when handling errors.
     
  2. cancer10

    cancer10 New Member

    Joined:
    Jul 12, 2008
    Messages:
    36
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    Webmaster
    Location:
    India
    I have this ASP code


    <%
    sub mysub
    mytestvariable = 111
    end sub


    call mysub
    response.write mytestvariable

    %>

    Why does the above code show BLANK when I response.write mytestvariable


    Shouldn't it output 111?
     
  3. MLuddyJr

    MLuddyJr New Member

    Joined:
    Sep 25, 2008
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    Software Developer
    Location:
    Fuquay Varina, NC
    The problem is that variables defined in subroutines have a private scope, meaning that they can't be accessed outside of that subroutine. Inside your subroutine you've assigned mytestvariable the value of 111, but outside the subroutine in the main body of code the variable doesn't exist. When your code gets to the response.write statement and sees mytestvariable it treats it as a new variable that has not been assigned a value. In order to allow your subroutine to assign a value to a variable that will be accessible by the rest of the code you have to declare the variable as public in the main body of code:

    Code:
    <%
    sub mysub
         mytestvariable = 111
    end sub
    
    Public mytestvariable
    call mysub
    Response.Write mytestvariable
    %>
    
    If you wanted a call to the subroutine to write out the variable without changing the scope of the variable you could also include the Response.Write inside the subroutine:

    Code:
    <%
    sub mysub
         mytestvariable = 111
         Response.Write mytestvariable
    end sub
    
    call mysub
    %>
    

    Another limitation is that subroutines do not return anything to the main body of code. If you wanted to assign a value to a private variable inside the subroutine but write the variable value in the main body of code, you would have to use a function instead of a subroutine and assign the function the value of the variable:

    Code:
    <%
    function myfunction
         mytestvariable = 111
         myfunction = mytestvariable
    end function
    
    Response.Write myfunction
    %>
    
     
  4. TPrice

    TPrice New Member

    Joined:
    Aug 24, 2010
    Messages:
    9
    Likes Received:
    1
    Trophy Points:
    0
    Thanks for this great explanation of subroutines. I am learning so much from this forum. This is precisely the information I needed to get my current project to do what I need it to. Now I can make more complex processes, I really appreciate this.
     

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