Skip to main content

Sub Procedures


In Visual Basic, there are many cases that we use “subs”. Sub procedure or a subroutine that does not return a value. It is commonly used piece of code which you will want to execute in various places in your program. Using this subroutine, you can minimize your code and find it easy to debug if something went wrong with your program. And this subroutine also can be called in any parts of the program.

Sub Procedure Syntax

[Modifiers] Sub SubName [(ParameterList)]
	[Statement]
End Sub

Modifiers – used to access level of the procedure; example: Public, Private, protected, Friend, Protected Friend and information regarding overloading, Overriding, Sharing and Shadowing.
SubName – it used to indicate the name of a subroutine.
ParameterList – the specified list of parameters.

Example:
This example will do the addition of the two values inside the sub and the output will be displayed when the sub is called from different sub. And here’s the following code:

  1. Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
  2. 'call the sub AddtwoValues
  3. AddtwoValues()
  4. End Sub
  5.  
  6. 'creata a sub
  7. Sub AddtwoValues()
  8. 'some declaration
  9. Dim num1 As Integer = 5
  10. Dim num2 As Integer = 7
  11. Dim total As Integer
  12. 'do the computation
  13. total = num1 + num2
  14. 'display the result
  15. MsgBox(total)
  16. End Sub

Output:



Passing Parameter By values
And these another example will do the adding the two values using the parameter.

  1. Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
  2. 'call the sub AddtwoValues
  3. 'using the two value parameter
  4. AddtwoValues(23, 45)
  5. End Sub
  6.  
  7. 'creata a sub with parameters
  8. Sub AddtwoValues(ByVal num1 As Integer, ByVal num2 As Integer)
  9. 'some declaration
  10. Dim total As Integer
  11. 'do the computation
  12. total = num1 + num2
  13. 'display the result
  14. MsgBox(total)
  15. End Sub

Output:

Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. After downloading it, you will need a program like Winzip to decompress it.

Virus note: All files are scanned once-a-day by SourceCodester.com for viruses, but new viruses come out every day, so no prevention program can catch 100% of them.

FOR YOUR OWN SAFETY, PLEASE:

1. Re-scan downloaded files using your personal virus checker before using it.
2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.

Comments

Add new comment

CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.