This is for those of you wanting to know how to generate random numbers. I will explain how to generate a random number from 1 to 100 in a text box.

Step 1: Create a textbox and name it txtrandom.

Step 2: Create a command button and name it cmdrandom.

Double-click on the button to write its code.
Type in this code:

Private Sub Cmdrandom_Click()

For i = 0 To 9
Txtrandom.Text = Format(((Rnd(i) * 100) + 1), "0")
Next i

End Sub

This will have put a completely random number in the textbox every time you click the button.

Recommended Answers

All 6 Replies

Why do you use For Next loop???
Here's how I would do it in .NET way:

Dim Gen As System.Random
Gen = New System.Random(My.Computer.Clock.TickCount)
Txtrandom.Text = Gen.Next(1, 101).ToString

A few points:
- I would use computer clock's TickCount as a seed number
- Next(1, 101) method generates integers from 1 to 100, the upper bound is exclusive
And finally these are pseudo random numbers after all.

This generates from 1 to 101 not from 1 to 100.

dear ninjastormns you can just change the following value Txtrandom.Text = Gen.Next(1, 101).ToString to Txtrandom.Text = Gen.Next(1, 100).ToString it will generates from 1 to 100.


In fact, the upper bound of the Gen.Next will never appear as one of the random numbers so if you want a number from 1 to 100 you must give 101 as the upper bound. As far as I am concerned it is brain dead but there you have it.

can u help for alphanumeric random generation? Malar

@malarsevli - do you just want some sort of random ID containing letters and numbers?
Or is it some sort of password generator you are trying to get?

If you have a SQL database, it has a field type GUID which will generate a randomish ID that uses numbers and letters (it is based on the computers network card and CPU Time)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.