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

What did Pito Salas invent?
Pito Salas, working for Lotus, popularized what would become to be pivot tables. It was released as Lotus Improv in 1989.
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,213,497
Messages
6,113,999
Members
448,543
Latest member
MartinLarkin

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