Search code examples
vbapowerpoint

Display random number in slide using VBA


I need to generate a random number between 1 and 30 and display it on every slide. I found the following code online:

Sub UpdateRandomNumber(oSh As Shape)
    Dim X As Long
    'Make the shape’s text a random number
    'X or less
    'Change 12 below to any number you’d like:
    X = 30
 
    oSh.TextFrame.TextRange.Text = CStr(Random(X))
End Sub
 
Function Random(High As Long) As Long
    'Generates a random number less than or equal to
    'the value passed in High
    Randomize
    Random = Int((High * Rnd) + 1)
End Function

Sub RandomNumber()

End Sub

I need the code to do one thing differently:
The object prompting the action is in the same spot on all slides. When generating and displaying a random number, all slides should be changed accordingly.
When I leave the slide, the previously generated number should be shown instead of the one that was previously generated on this slide.


Solution

  • This creates a random number between 1 and 30. Change the shape name to the actual shape used in your file:

    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 = "Rectangle 3" Then
                    oShape.TextFrame.TextRange.Text = ShapeNumber
                End If
            Next oShape
        Next oSlide
    End Sub