Displaying Random Number

Blue Cheeseburger

New Member
Joined
Feb 23, 2021
Messages
14
Office Version
  1. 365
Platform
  1. Windows
I have a spreadsheet where the user clicks a button, and a random number is generated and displayed. If the new random number is the same as the previous number, it's hard to be sure that anything happened. I tried writing code so that when the user clicks the button, the previous number is cleared, and a MsgBox is displayed. When the user clicks the MsgBox, the new number is displayed. Is there a way to do something like this automatically, without requiring the user to click on a MsgBox? Thanks.
 

Excel Facts

Lock one reference in a formula
Need 1 part of a formula to always point to the same range? use $ signs: $V$2:$Z$99 will always point to V2:Z99, even after copying
Here is my code:

VBA Code:
Private Sub CommandButton4_Click()
Dim r As Integer

Range("ChosenNumber").Value = 0

Randomize
r = Int((6 - 1 + 1) * Rnd + 1)

MsgBox "Continue"

Range("ChosenNumber").Value = r

End Sub
 
Upvote 0
Your level of randomness is already pretty low, so I would solve the problem by not letting the function pick the same number twice in a row.

VBA Code:
Private Sub CommandButton4_Click()
    Dim r As Integer
    
   'Randomize
    Do
        r = Application.WorksheetFunction.RandBetween(1, 6)
    Loop Until r <> Range("ChosenNumber").Value
    
    Range("ChosenNumber").Value = r
End Sub
 
Upvote 0
Thank you, rlv01. I had never tried using the RAND function. I think it's easier to understand than how I was doing it.
 
Upvote 0

Forum statistics

Threads
1,215,096
Messages
6,123,074
Members
449,093
Latest member
ripvw

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top