Random number generator button

TessieBear99

New Member
Joined
Aug 26, 2018
Messages
20
Office Version
  1. 365
Platform
  1. Windows
I need to be able to generate a random number between 1 and x, with x being the number of people listed in my worksheet. The formula I have to do this works, it is:
Excel Formula:
=RAND()*(COUNTIF(B2:B198,"<>"&"")-1)+1

Now I need to create a macro to assign to my button so that when the button is clicked, that formula runs and the value is pasted into E1. I've tried this with the following code but when I run it, it comes out with "TRUE" in E1 instead of the value.
VBA Code:
Sub RandomNumberGenerator()

'Generates random number between 1 and total number of names listed

    Range("E1").Formula = "=RAND()*(COUNTIF(B2:B198," <> " & "")-1)+1"
    Range("E1").Copy
    Range("E1").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    Application.CutCopyMode = False
    
End Sub

Can someone please assist?
 

Excel Facts

Excel Joke
Why can't spreadsheets drive cars? They crash too often!
Maybe the below will do it?

VBA Code:
Sub test()
    With Application
        Range("E1") = .RandBetween(1, .CountA(Range("B2:B198")))
    End With
End Sub

Or another option:

VBA Code:
Sub test2()
    Range("E1") = Evaluate("RANDBETWEEN(1," & Application.CountA(Range("B2:B198")) & ")")
End Sub
 
Upvote 1
Solution

Forum statistics

Threads
1,224,813
Messages
6,181,117
Members
453,021
Latest member
Justyna P

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