把0 ~ 9 这10个数字放在数组M中; N 从 1 到 4 循环: 产生一个[N + 1, 10]之间的随机数R; 把M中第N个数和第R个数交换。 NEXT N这时候取出前面4个数就可以了。
Private Sub Command1_Click() Dim i As Integer Dim strTmp As String Dim strRet As String For i = 1 To 4 Do strTmp = Int(Rnd() * 10) Loop While InStr(1, strRet, strTmp) > 0 strRet = strRet + strTmp Next MsgBox strRet End Sub
我这段代码虽然罗嗦,但是非常有效哟!Private Sub Command1_Click() Dim x As Integer '欲生成的四位随机数 Dim i As Integer Dim n(1 To 4) As Integer l1: n(1) = Int(Rnd * 10) If n(1) = 0 Then GoTo l1 '第一位数字不能为0 l2: n(2) = Int(Rnd * 10) If n(2) = n(1) Then GoTo l2: l3: n(3) = Int(Rnd * 10) If n(3) = n(1) Or n(3) = n(2) Then GoTo l3 l4: n(4) = Int(Rnd * 10) If n(4) = n(1) Or n(4) = n(2) Or n(4) = n(3) Then GoTo l4
x = n(1) * 1000 + n(2) * 100 + n(3) * 10 + n(4)
MsgBox x '显示结果
End Sub
Dim col As Collection Dim i As Integer Dim Index As Integer Dim s As String Set col = New Collection For i = 1 To 9 col.Add i Next i Randomize For i = 1 To 4 Index = (col.Count - 1) * Rnd + 1 s = s & CSng(col(Index)) col.Remove Index Next i Set col = Nothing
上面没考虑0,改一下: Dim Col As Collection Dim i, j, Index As Long Dim s As String 100 Set col = New Collection For i = 0 To 9 Col.Add i Next i Randomize For i = 1 To 4 Index = (Rnd * (Col.Count - 1)) + 1 s = s & CSng(Col(Index)) Col.Remove Index Next i Set Col = Nothing j = CLng(s) If j < 1000 Then GoTo 100 Debug.Print s
N 从 1 到 4 循环:
产生一个[N + 1, 10]之间的随机数R;
把M中第N个数和第R个数交换。
NEXT N这时候取出前面4个数就可以了。
Dim i As Integer
Dim strTmp As String
Dim strRet As String
For i = 1 To 4
Do
strTmp = Int(Rnd() * 10)
Loop While InStr(1, strRet, strTmp) > 0
strRet = strRet + strTmp
Next
MsgBox strRet
End Sub
Dim x As Integer '欲生成的四位随机数
Dim i As Integer
Dim n(1 To 4) As Integer
l1:
n(1) = Int(Rnd * 10)
If n(1) = 0 Then GoTo l1 '第一位数字不能为0
l2:
n(2) = Int(Rnd * 10)
If n(2) = n(1) Then GoTo l2:
l3:
n(3) = Int(Rnd * 10)
If n(3) = n(1) Or n(3) = n(2) Then GoTo l3
l4:
n(4) = Int(Rnd * 10)
If n(4) = n(1) Or n(4) = n(2) Or n(4) = n(3) Then GoTo l4
x = n(1) * 1000 + n(2) * 100 + n(3) * 10 + n(4)
MsgBox x '显示结果
End Sub
Dim i As Integer
Dim Index As Integer
Dim s As String
Set col = New Collection
For i = 1 To 9
col.Add i
Next i
Randomize
For i = 1 To 4
Index = (col.Count - 1) * Rnd + 1
s = s & CSng(col(Index))
col.Remove Index
Next i
Set col = Nothing
Dim i, j, Index As Long
Dim s As String
100
Set col = New Collection
For i = 0 To 9
Col.Add i
Next i
Randomize
For i = 1 To 4
Index = (Rnd * (Col.Count - 1)) + 1
s = s & CSng(Col(Index))
Col.Remove Index
Next i
Set Col = Nothing
j = CLng(s)
If j < 1000 Then GoTo 100
Debug.Print s