Skip to content

Instantly share code, notes, and snippets.

@stden
Created April 4, 2017 00:47
Show Gist options
  • Save stden/59f9e2fd64e6c88c90cf2b64bf1f6ee9 to your computer and use it in GitHub Desktop.
Save stden/59f9e2fd64e6c88c90cf2b64bf1f6ee9 to your computer and use it in GitHub Desktop.
Sub Start()
Dim nrOfValues As Long, first As Long, last As Long
Dim xy As Range, max As Long
Set xy = Range("A1")
first = Range("first").value
last = Range("last").value
nrOfValues = Range("nr_of_values").value
' Clear old values
Call DeleteValues(xy)
' Generate new random values first..last number = nrOfValues
Call GenerateNumbers(xy, first, last, nrOfValues)
Range("percentOfEven").value = PercentOfEvenNumbers(xy, nrOfValues)
Range("smallestPos").value = SmallestPosNum(xy, nrOfValues)
End Sub
' Percentage of even numbers (PercentOfEvenNumbers)
' xy - range of source cells
' nrOfValues - number of values
Function PercentOfEvenNumbers(xy As Range, nrOfValues As Long)
Dim i, numberOfEven
numberOfEven = 0
For i = 1 To nrOfValues
' X mod Y
If xy(i, 1) Mod 2 = 0 Then ' If current value is even
numberOfEven = numberOfEven + 1 ' Increase counter of even numbers
End If
Next i
PercentOfEvenNumbers = numberOfEven / nrOfValues
End Function
' The smallest number that is positive (SmallestPosNum)
Function SmallestPosNum(xy As Range, nrOfValues As Long)
Dim i, min, value
min = xy(1, 1)
For i = 1 To nrOfValues
value = xy(i, 1)
If value > 0 And value < min Then
min = value
End If
Next i
SmallestPosNum = min
End Function
Sub GenerateNumbers(xy As Range, first As Long, last As Long, howMany As Long)
Dim i
For i = 1 To howMany
xy(i, 1) = Int(Rnd() * (last - first + 1) + first)
Next i
End Sub
Sub DeleteValues(xy As Range)
xy.CurrentRegion.ClearContents
End Sub
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment