Writing Functions in VB
Functions are very useful and convenient methods in programming. It is basically used to generate data by passing a data value into the function and then obtain a result from it. Like Sub procedure, a function is eclared with a Function keyword. See the example below on how to create a function.
Public Function Multiply(ByVal InputData As Double) As Double
Dim OutputData As Double
OutputData = InputData * 2
Return(OutputData)
End Function
As can be seen in the example above, The function is a 'Public' declaration type which means this function can be access from anywhere in the project. For instance, if this function is specifically created for access from within this module only, 'Private' type will be used instead. The next item Multiply is the name of this function. Further on, the ByVal InputData As Double section in the example above declares the input variable of this function. It is the entry point into the Function. The following As Double at the end of the function procedure is the declaration of the output data type, that is, the data that the function ultimately returns to the caller. Notice that inside the function, a Return() call exists and this is necessary as it is the exit point leading the way out the function.
Unlike Sub procedure which doesn't has an exit point, a function has at least an entry point and an exit point. If a function requires more than one input data, commas can be used to separate between the declaration of input data. See the second example illustrated below.
Public Function Multiply(ByVal InputData1 As Double, ByVal InputData2 As Double) As Double
Dim OutputData As Double
OutputData = InputData1 * InputData2
Return(OutputData)
End Function
To call the function above in your Visual Basic code, just add the following line as follows
TextBox1.Text = Multiply( 54 , 3 )
The value obtained in TextBox1.Text will be 162. Hence, that's how you can create functions in Visual Basic programming. It helps you better organize your programming code making it easier to read and best of all, Function can be reused again and again everywhere in your project.
See a function example on Fahrenheit To Celcius Converter
and also Celcius To Fahrenheit Converter
See Also Writing A Sub
Subscribe to:
Post Comments (Atom)

0 comments
Post a Comment