Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Wanet Telecoms Ltd on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

code to generate random integer variable 1

Status
Not open for further replies.

haytatreides

IS-IT--Management
Oct 14, 2003
94
US
does anyone know code to generate a random integer for a variable??? i want to have an if statement execute 20% of the time, I figure that if i can get a variable to take an integer from 1-100 and if that number is 1-20 then execute. anyone know how i can do this?
 
Private Sub Command1_Click()
Dim RndmInt As Integer

Randomize
RndmInt = Int(Rnd * 100)
End Sub
 
Since Rnd() generates a number between 0 and 1, you could just use this for your "If" statement:
Code:
If Rnd() < 0.21 Then
   ' Do whatever
End If



VBAjedi [swords]
 
ok, i lied.

it didn't work. i tried the format

MyValue = Cint(Int((101 * Rnd()) + 1))

and it is telling me that the object method isn't supported. I am guesssing because rnd() is a .net function and access 2002 uses VB6.3 could that be it? or am i just doing it wrong?

hayt
 
your guessing? Because you could just do a F1 on rnd() to see if its in the vba help files and look at it there.
 
hayt,

Your code works fine in Excel VBA. . . but I'm not seeing why you want to take that approach. Unless you need a random number between 1 and 100 for something else?

The way I used Rnd() in my example &quot;If&quot; statement means you don't have to store the random number in a variable at all. It just executes whatever is inside the &quot;If&quot; about 20% of the time (on my single test run it was 18%).

VBAjedi [swords]
 
i got it. the cint doesn't work no need for it. thanks all
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top