title: discrete function by using VBA
body: <p>I am trying to create Discrete function by using VBA code.<br>
  It works sometime, but I also received "Subscript of range error" message. Anyone can figure out the reason?</p>
  
  <pre><code>Function Discrete6()    
      Dim value As Variant, prob As Variant, i As Integer
      Dim uniform As Double, cumProb As Variant
  
      value = Array(5, 10, 12)
      prob = Array(0.2, 0.3, 0.5)
      uniform = Rnd
      cumProb = prob(1)
  
      i = 1
      Do Until cumProb &gt; uniform
          i = i + 1
          cumProb = cumProb + prob(i)
      Loop
  
      Discrete6 = value(i)
  End Function
  </code></pre>