2017-10-23 22 views
1

以下のような乱数生成コードがあります。あらかじめ定義された集団範囲から "x"量の数字を生成します。それを生成するには時間がかかり、より効率的であれば私は迷っていますか?数字は複製できません。VBAランダム図ジェネレータ - 効率が良い?

Private Sub CommandButton1_Click() 

Dim real_rnd As Double 
Dim letter_lng As Long 
Dim lngCounter As Long 
Dim lngRandomFigureList(2000) As Long 
Dim i As Integer 
Dim lngPopulation As Long 
Dim intNoOfSamples As Integer 
Dim strCell As String 
Dim blnDuplicate As Boolean 
Dim blnFound As Boolean 


Sheets("random selection").Select 
Range("Pop").Select 
lngPopulation = ActiveCell.Value 

Range("NoSamp").Select 
intNoOfSamples = ActiveCell.Value 

Range("Figures").Select 
    Range(Selection, Selection.End(xlDown)).Select 
    Selection.ClearContents 
    Range("Figures").Select 

Range("Figures").Select 

For lngCounter = 1 To intNoOfSamples 
    blnDuplicate = True 
    Do While blnDuplicate = True 
     real_rnd = Rnd() * (lngPopulation - 1) + 1 
     letter_lng = Abs(real_rnd) 
     blnFound = False 
     For i = 1 To lngCounter - 1 
      If letter_lng = lngRandomFigureList(i) Then 
       blnFound = True 
      End If 
     Next i 
     If blnFound = False Then 
      blnDuplicate = False 
     End If 
    Loop 

    lngRandomFigureList(lngCounter) = letter_lng 
    strCell = "A" & 6 + lngCounter 
    Range(strCell).Select 
    ActiveCell.Value = letter_lng 
Next lngCounter` 
+0

は '選択... selection'コードを取り除きます。それはプログラムを遅くする – jsotola

答えて

0

は選択を取り払う:

With Sheets("random selection") 
    lngPopulation = .Range("Pop").Value 
    intNoOfSamples = .Range("NoSamp").Value 
    Range(.Range("Figures"), .Range("Figures").End(xlDown)).ClearContents 


    For lngCounter = 1 To intNoOfSamples 
     blnDuplicate = True 
     Do While blnDuplicate = True 
      real_rnd = Rnd() * (lngPopulation - 1) + 1 
      letter_lng = Abs(real_rnd) 
      blnFound = False 
      For i = 1 To lngCounter - 1 
       If letter_lng = lngRandomFigureList(i) Then 
        blnFound = True 
       End If 
      Next i 
      If blnFound = False Then 
       blnDuplicate = False 
      End If 
     Loop 

     lngRandomFigureList(lngCounter) = letter_lng 
     .Range("A" & 6 + lngCounter).Value = letter_lng 
    Next lngCounter 
End With 
+0

素晴らしい作品、そのような迅速な応答ありがとう:) – KaBi

関連する問題