An Improved Custom Random Numbers Function

In this article, we will create a custom function to generate random decimal numbers between the defined ranges.

Raw data for this example consists of lowest value and highest value of the range and number of decimal places required in decimal numbers.

ArrowRawData

We have created a custom function “RandomNumbers” to generate random decimal numbers between the defined lowest and highest numbers. This function takes lowest value, highest value and number of decimal places required as input and returns random decimal numbers as output.

ArrowOutput

Code explanation

Randomize function

Randomize function is used to initialize the RnD function of the random-number generator and assign it a new seed value.

RnD function

RnD function returns a random number of single data type.

Round function

Round function is used to limit the number of decimal places.

Syntax of Round function

Round(value,Number_of_decimal_places)

 

Please follow below for the code


Option Explicit
Function RandomNumbers(Lowest As Double, Highest As Double, _
Optional Decimals As Integer = 0)

Randomize

RandomNumbers = Round((Highest - Lowest) * Rnd + Lowest, Decimals)

End Function

 

If you liked this blog, share it with your friends on Facebook. Also, you can follow us on Twitter and Facebook.

We would love to hear from you, do let us know how we can improve our work and make it better for you. Write to us at info@exceltip.com

Leave a Reply

Your email address will not be published. Required fields are marked *

Terms and Conditions of use

The applications/code on this site are distributed as is and without warranties or liability. In no event shall the owner of the copyrights, or the authors of the applications/code be liable for any loss of profit, any problems or any damage resulting from the use or evaluation of the applications/code.