Saputnik
Saputnik

Reputation: 35

Random number macro does not return desired value

I have created a simple module that is meant to do following:

Problem is, it returns assigned value "lower" even if the number is higher than or equal to 500, i.e., all assigned values, 100,000 of them, are "lower"!

I'd appreciate if someone can check where I'm going wrong with this code; I'm not an expert in VBA, but I thought I could do this myself... :\

Sub MacroRanNum()

   Dim RunNum As Integer
   Dim Outcome As String

For i = 1 To 100000

   Randomize
   RanNum = Int((999 - 0 + 1) * Rnd + 0)

   If RunNum < 500 Then
   Outcome = "Lower"
   ElseIf RunNum >= 500 Then
   Outcome = "Higher"
   Else
   Outcome = "Error!"
   End If

Sheets("podatak").Cells(i, 1) = RanNum
Sheets("podatak").Cells(i, 2) = Outcome

Next i

End Sub

Upvotes: 0

Views: 59

Answers (2)

SchonWieder
SchonWieder

Reputation: 213

You are mixing your variable names. You define and check against RunNum but your random value and your display value are RanNum. You are never testing against the value you randomly generated.

Upvotes: 1

Peter Lang
Peter Lang

Reputation: 55524

Your variable name is

RanNum
but you check for
RunNum

OPTION EXPLICIT could help to avoid such problems.

Upvotes: 2

Related Questions