Posted on December 12th, 2005
22933 views In this tutorial, you will learn how to use functions in Visual Basic. Functions are quite the same as calling a public sub but they are much more useful. You usually use them to calcute things. But what's the difference then? In a functions, you can specify parameters and return a final value. You can have as much parameters as you like but only one return value. For example, let's take a "magic box". We enter "3" and "6" as parameters and the result is "9".
It's quite obvious that the magic box contains a " + " so it does 3 + 6 and return 9. We'll return into VB now, create a new project and form window. Sure you can put functions in your form window but they are usually placed in a module. To create one, right-click your project item in the objectlist then select ADD > MODULE. Now a code window appears. That's the place the write your functions. Public Function var1(ByVal var2 As Integer, ByVal var3 As Integer) As Integer 'Your code here End Function Public Function = Define a new function In the function, you could then put "var1 = var2 + var3" which will return the addition of both variables and return the answer in var1 Public Function var1(ByVal var2 As Integer, ByVal var3 As Integer) As Integer var1 = var2 + var3 End Function Now that you know how to make functions, you'll learn how to use them. Nothing is more easier. In your form window or from another function: var1(parameter1_value, parameter2_value) var1 is the name of the function and inside are the parameters value, you can also use variables to define values. A working example of calling a function would be: Private Sub cmdMsg_Click() MsgBox Str(var1(3, 6)) End Sub You've probably seen that I used ByVal when writing the function. If you put nothing, it will act as "ByRef" by default. Let's see what's the difference and why you should always use ByVal when using ByVal, it creates a different variable from the parameter. Visual Basic is the only programming language to have ByRef by default, normally you should have ByVal but well, try to understand why... The only time you HAVE TO use ByRef is when you use a table variable as a parameters. Using ByVal to transfer a table use heavy CPU resources especially if you have a huge table which happens often. By that, i mean variables declared as (I,J) and more. The great thing with Functions is that you can call them from themselves, just like you would do using a "while". Just use the exact same code as you would call a function normally. Be sure not to create an infinite loop. |