Using Functions is very similar to using Subroutines but their main purpose is to accept certain inputs, process them and pass some output on to the calling Function or Subroutine. They are two types of Functions, the In-built Functions (or internal Functions) and the Functions created by the programmers or User-Defined Functions as they are better known.
In-built FunctionsMicrosoft provides users with some powerful In-built Functions. Based on the kind of actions that the functions perform, they are broadly classified into Mathematical Functions, Formatting Functions and String Manipulation Functions. The In-built Functions are quite a few and it would require a separate study to dwell into all of them. Also, for beginners, it is not advisable to study all of them. As you gain experience, you will naturally learn more about these functions. As for now, let's see a basic example of a string manipulation Function.
Len(string or expression)The Len Function returns the length of the string or expression. For example, Len("Anthony Hopkins") will return 15.
User-Defined FunctionsAlthough Microsoft provides a wide range of In-built Functions, you really can't expect them to satisfy the needs of all the users. So, many a times, we need to create our own functions which are known as User-Defined Functions. User-Defined Functions are written very much like subroutines that take arguments. The syntax is:
Function functionname (Arg As datatype,...) As datatypeLet's see an example. We will write a function to pass a value as Fahrenheit and get the Celsius value as an output. The formula for that is Celsius = 5 * (Fahrenheit - 32) / 9
Function FahToCel(Fahrenheit As Double) As DoubleWhile using functions, you can call a Function procedure on the right side of an expression when you want to use the value returned by the function. Here is an example.
FahToCel = 5 * (Fahrenheit - 32) / 9
CelValue=FahToCel(100)Ideally, when you need to return a value you have to create and use a Function. Use a Sub procedure when you do not need to return any value. You will learn more in future articles.
Back to Visual Basic for Beginners