-
Anyone Know how to random 5 number, and when i click command button 1st time, it has a msgbox with a randomize number(ex:2), then the number(2) is cancel. And i click again, a randomize number(5),then 5 is cancel. That means what i click 5 times command button, there is no number left, Empty. Can You tell me what the code, plz!! Need it Ugently!!
-
Can you rephrase that question ?
- jamie.
-
leung, do you mean the number must append once only?
Code:
Option Explicit
Private dict As Dictionary
Private Sub form_load()
Set dict = New Dictionary
dict.CompareMode = TextCompare
End Sub
Private Sub Command1_Click()
Dim i As Integer
If dict.Count = 5 Then
dict.RemoveAll
Msgbox "No More number!"
Else
i = GetNum
Do While Not dict.Exists(i)
dict.Add i, i
MsgBox "New Number is " & i
DoEvents
Loop
End Sub
Private Function GetNum()
Randomize Timer
GetNum = Int((5 * Rnd) + 1)
End Function
Enjoy the sample code.
-
Dictionary??
Nice code, but I get an error stating: udt not defined and Dictionary is marked.
What is Dictionary?
-
onerrorgoto, Disctionary is an VB Script Object and you need to reference to the Microsoft Script Runtime Library (Scrrun.dll) at Project|References
Cheers!
-
Code:
Private Sub Command1_Click()
Dim intRandom As Integer
Static intAdded As Integer
Dim bFound As Boolean
Dim intDummy As Integer
Static colRandomNumbers As New Collection
Randomize
If intAdded = 5 Then
MsgBox "No more numbers available"
Exit Sub
End If
Do Until bFound
intRandom = Int(5 * Rnd + 1)
On Error Resume Next
intDummy = colRandomNumbers.Item(CStr(intRandom))
bFound = (Err = 0)
If bFound Then
' It's already in the collection
Err.Clear
Else
' It's not, so add it
colRandomNumbers.Add intRandom, CStr(intRandom)
bFound = True
intAdded = intAdded + 1
MsgBox "Number is " & intRandom
End If
Loop
End Sub
-
Here's another way:
Code:
Option Explicit
Dim intArray(0 To 4) As Integer
Public Sub command1_click()
Static Counter As Integer
Static Y As Integer
Dim x As Integer
Dim I As Integer
Dim Exists As Boolean
Randomize Timer
Counter = Counter + 1
If Counter > 5 Then MsgBox "Empty": Exit Sub
Handle:
I = Int(Rnd * 5) + 1
For x = LBound(intArray) To UBound(intArray)
If I = intArray(x) Then
Exists = True
Exit For
End If
Next x
If Exists = True Then
Exists = False
GoTo Handle:
End If
intArray(Y) = I
Y = Y + 1
Select Case I
Case Is = 1: MsgBox I: Exit Sub
Case Is = 2: MsgBox I: Exit Sub
Case Is = 3: MsgBox I: Exit Sub
Case Is = 4: MsgBox I: Exit Sub
Case Is = 5: MsgBox I: Exit Sub
End Select
-
Martin, never think abt to use the Collection object.
Thank to remind me abt this object. :cool:
[Edited by Chris on 01-11-2001 at 01:35 AM]