HERBERS Excel-Forum - die Beispiele

Thema: Auswahl von Werten nach dem Zufallsprinzip

Home

Gruppe

Allgemein

Problem

Aus dem Bereich A1:A10 sollen nach dem Zufallsprinzip 5 Werte ausgewählt werden, ohne dass sich diese wiederholen. Die Werte sollen in ein Array eingelesen und gemeldet werden.

Lösung
Geben Sie den nachfolgenden Code in ein Standardmodul ein und weisen Sie ihn einer Schaltfläche zu.
StandardModule: Modul1

Sub Zufall()
   Dim rng As Range, rngAll As Range
   Dim arr(1 To 5) As String
   Dim iRandomize As Integer
   Dim sMsg As String
   Application.ScreenUpdating = False
   Set rngAll = Range("B1:B5")
   Randomize
   rngAll.ClearContents
   For Each rng In rngAll.Cells
      iRandomize = Int((5 * Rnd) + 1)
      Do Until WorksheetFunction.CountIf(rngAll, iRandomize) = 0
         iRandomize = Int((5 * Rnd) + 1)
      Loop
      rng.Value = iRandomize
   Next rng
   For iRandomize = 1 To 5
      arr(iRandomize) = Cells(iRandomize, 2).Value
   Next iRandomize
   Columns(2).ClearContents
   For iRandomize = 1 To 5
      sMsg = sMsg & Cells(arr(iRandomize), 1).Value & vbLf
   Next iRandomize
   MsgBox sMsg
   Application.ScreenUpdating = True
End Sub