VBA Function – Populating a Range With Random Values
Populate Cells With Random Values
The following code will populate a given range with a random number between 0 and 1000:
Sub Randomise_Range(Cell_Range As Range) ' Will randomise each cell in Range Dim Cell 'Turn off screen alerts Application.ScreenUpdating = False For Each Cell In Cell_Range Cell.Value = Rnd * 1000 Next Cell Application.ScreenUpdating = True End Sub
The code “Application.ScreenUpdating =FALSE” and “Application.ScreenUpdating = TRUE” serve to turn off and turn on screen alerts – making the code much faster to run.
It can be set up via a click event, with the main routine specifying the range:
Private Sub CommandButton1_Click() Randomise_Range (Sheets("Sheet3").Range("A1:T8000")) End Sub
So this case, cells A1:T8000 on sheet 3 are populated with random numbers – once the command button 1 is clicked.
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro – A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!