It also enables you to divide long procedures into small manageable functions. This is very useful in that it stops you from having to write the same code over and over again. We can then call the above function from a Sub Procedure in order to work out how many pounds a specific amount of kilos are.Ī function can be a called from multiple procedures within your VBA code if required. Function ConvertKilosToPounds (dblKilo as Double) as Double These parameters can be referred to as Arguments. You can also assign a parameter or parameters to your function. In the above example, the GetRange Function is called by the Sub Procedure to bold the cells in the range object. You can also call the GetRange function from a Sub Procedure. The value of 50 would always be returned. Once you create a function, you can call it from anywhere else in your code by using a Sub Procedure to call the function. If you were to use the above function in your VBA code, the function would always return the range of cells A1 to G4 in whichever sheet you are working in. You can also create functions that refer to objects in VBA but you need to use the Set Keyword to return the value from the function. If you were to run the function, the function would always return the value of 50. You may want to create a function that returns a static value each time it is called – a bit like a constant. The function can then be defined as a data type indicating the type of data you want the function to return. To create a function you need to define the function by giving the function a name. VBA functions can also be called from inside Excel, just like Excel’s built-in Excel functions. This is extremely useful if you want VBA to perform a task to return a result. A Function Procedure is able to return a value to your code. When you write code in VBA, you can write it in a Sub Procedure, or a Function Procedure. VBA contains a large amount of built-in functions for you to use, but you are also able to write your own. This tutorial will teach you to create and use functions with and without parameters in VBA Using a Function from within an Excel Sheet.Calling a Function from a Sub Procedure.
0 Comments
Leave a Reply. |