47khz
47khz

Reputation: 13

Random number generator that always produces a number different from the previous random number

So I've been working on a Vocabulary Soccer game for my students on PowerPoint. Thanks to John Korchok (Display random number in PowerPoint using VBA) I was able to implement a VBA code that provides me with a random number when I hit a certain shape (necessary in order to let my students know whose turn it is). The code looks like this and works perfectly fine:

    Sub ShapeNumber()
    Dim X As Long
    Dim ShapeNumber As String
    Dim oSlide As Slide
    Dim oShape As Shape

    X = 30
    Randomize
    ShapeNumber = Int((X * Rnd) + 1)
    For Each oSlide In ActivePresentation.Slides
        For Each oShape In oSlide.Shapes
            If oShape.Name = "RandomNumber Shape" Then
                oShape.TextFrame.TextRange.Text = ShapeNumber
            End If
        Next oShape
    Next oSlide
End Sub

I've been wondering if the code could be modified so that it always produces a number different from the number that was generated the last time. In practice I've realized that my students tend to be confused when I hit the shape and nothing changes (they don't know if it's the same number again or whether it simply didn't work).

Upvotes: 0

Views: 449

Answers (2)

Tim Williams
Tim Williams

Reputation: 166196

You can keep track of the last number:

Dim LastNumber As Long

Sub ShapeNumber()
    Dim X As Long
    Dim ShapeNumber As Long
    Dim oSlide As Slide
    Dim oShape As Shape

    X = 30
    Randomize
    Do
        ShapeNumber = CLng((X * Rnd) + 1)
    Loop While ShapeNumber = LastNumber

    LastNumber = ShapeNumber 

    For Each oSlide In ActivePresentation.Slides
        For Each oShape In oSlide.Shapes
            If oShape.Name = "RandomNumber Shape" Then
                oShape.TextFrame.TextRange.Text = ShapeNumber
            End If
        Next oShape
    Next oSlide

End Sub

Upvotes: 2

JMP
JMP

Reputation: 4467

Initialize with:

X = 30
Randomize
ShapeNumber = Int(X * Rnd)
X = X - 1

To generate numbers use:

ShapeNumber = (ShapeNumber + Int(X * Rnd) + 1) Mod 30

and add the 1 back in here:

oShape.TextFrame.TextRange.Text = ShapeNumber + 1

Upvotes: 0

Related Questions