Quantcast
Viewing all articles
Browse latest Browse all 1449

Populate Unique Number Array

Hello everyone I thought I'd post an example in the codebank since I see this asked by different people about every week. This function returns an array of Unique numbers from a specific number to a specific number.

For example you need 20 unique numbers (no numbers can be the same) from 1 to 80 .
Code:

Private Function UniqueNumberArray(FromNumber As Integer, ToNumber As Integer, ArraySize As Integer) As Integer()
Dim RndCol As New Collection
Dim RndArr() As Integer
Dim RndNum As Integer
Dim i As Integer
 
  Randomize
 
    ReDim RndArr(ArraySize - 1)
 
    For i = FromNumber To ToNumber
      RndCol.Add CStr(i)
    Next
   
    For i = 0 To ArraySize - 1
      RndNum = ((RndCol.Count - 1) - FromNumber + 1) * Rnd + FromNumber
      RndArr(i) = RndCol.Item(RndNum)
      RndCol.Remove RndNum
    Next
 
  UniqueNumberArray = RndArr
End Function

Private Sub Command1_Click()
Dim MyUniqueNumbers() As Integer
Dim i As Integer
  MyUniqueNumbers = UniqueNumberArray(1,80,20)
  For i = 0 to 19 'It will be indexed from 0, so 20 numbers (0 to 19)
    Debug.Print MyUniqueNumbers(i)
  next
End Sub

Please feel free to post more functions similar to this one, since we keep repeating ourselves we could simply tell them to go to this codebank link and study how to do it.

Viewing all articles
Browse latest Browse all 1449

Trending Articles