Function

For better understanding what is meant by function is just like a formula where in you can return a value. Function is somewhat different from Subs, since sub cannot return a value.

For example:

     Function MySum(x, y) As Integer
    
          MySum = x + y

    End Function



You make an addition function. Inside the Function is your formula. When you execute this function, you just need to put values inside.

Try copy the code above and paste it in your vba editor.

In your excel sheet, click any cell then type "=", select MySum.
You just need to put the values and it will be calculated.

Let's try another example by putting Function inside the Sub.


You will ask, formula inside the Function procedure can also put directly inside the Subroutine procedure? Why need to separate.

This is because I will use the Function in other Subroutines too. Meaning, this can be called anytime without reconstructing the codes.

Try to run the code.

Our next topic is about userform.

No comments:

Post a Comment