AW: elegantere Loesung...
18.02.2012 06:42:01
fcs
Hallo Heiko,
man kann alternativ auch direkt ein Objekt ohne doppelte Einträge erstellen. Dabei erfordert in der 2. Variante das Scripting.Dictionary-Objekt einen besonders kurzen Code.
Zusätzlich solltest du die Randomize-Zeile übernehmen. Dein Code liefert sonst nach jedem Öffnen der Datei die gleiche Serie von Zufallszahlen.
Gruß
Franz
Sub testRandomLoop2()
Dim objCollection As New Collection, i As Integer, j As Integer
Dim loop1 As Long, strMsg As String
Randomize
Const AnzZahlen As Integer = 7
On Error GoTo Fehler
Do Until j = AnzZahlen
i = Int((AnzZahlen * Rnd) + 1)
objCollection.Add Item:=i, Key:=CStr(i)
'weitere Operationen
j = j + 1
Resume_Loop:
loop1 = loop1 + 1
Loop
'Testanzeige
strMsg = ""
i = 1
strMsg = strMsg & objCollection(i)
For i = 2 To objCollection.Count
strMsg = strMsg & " - " & objCollection(i)
Next
MsgBox j & ", " & loop1 & vbLf & strMsg
Fehler:
With Err
Select Case .Number
Case 0 'alles OK
Case 457 'Fehler tritt auf, wenn doppelter Schlüssel in Collection eingetragen werden _
soll
Resume Resume_Loop
Case Else
MsgBox "Fehler-Nr.: " & .Number & vbLf & .Description
End Select
End With
'Variablen aufräumen
Set objCollection = Nothing
End Sub
Sub testRandomLoop3()
Dim objDic As Object, arrWerte
Dim i As Integer
Dim loop1 As Long, strMsg As String
Randomize
Const AnzZahlen As Integer = 7
Set objDic = CreateObject("Scripting.Dictionary")
Do Until objDic.Count = AnzZahlen
i = Int((AnzZahlen * Rnd) + 1)
objDic(i) = 0 'Nur Unikate sammeln
'weitere Operationen
loop1 = loop1 + 1
Loop
'Testanzeige
arrWerte = objDic.keys
strMsg = ""
i = LBound(arrWerte)
strMsg = strMsg & arrWerte(i)
For i = i + 1 To UBound(arrWerte)
strMsg = strMsg & " - " & arrWerte(i)
Next
MsgBox objDic.Count & ", " & loop1 & vbLf & strMsg
'Variablen aufräumen
Set objDic = Nothing: Erase arrWerte
End Sub