WhenElephantsFly
WhenElephantsFly

Reputation: 13

Convert string to VBA Global Variable

I'm using VBA in PowerPoint and have over 50 shapes on a slide, all of which are named. To update the color of the shape, I reference a slide later in the presentation. The slide numbers are stored as global variables and assigned in a sub (slide nums stay constant):

Sub getSlideNum()
    example1_SlideNum = 25
    example2_SlideNum = 26
    example3_SlideNum = 27
    etc.
End Sub

Based off the shapes name, I'm able to use "example1", "example2", "example3", etc. I then concatenate it with "_SlideNum" giving me the variable name.

Instead of using If Statements or a Select Case to assign each variable their slide, I want to have a short function like so:

Function getSlide(shpName As String)

     Call getSlideNum    'get the slide num for each from the previously mentioned sub

     Dim p As Variant 
     p = shpName & "_SlideNum"

     getSlide = p

End Function

As expected, getSlide returns the string example1_SlideNum and NOT 25.

Is there a way to convert the string into the variable so it uses the stored value rather than the string text?

It would be nice to have a short function like above instead of typing up 50 or so Select Case statements.

Upvotes: 1

Views: 652

Answers (1)

JNevill
JNevill

Reputation: 50263

As mentioned in my comment, a dictionary would be a good choice to store these globals.

First go to Tools>>References and choose the Microsoft Scripting Runtime enter image description here

Using the dictionary object:

Private SlideDict As Dictionary

Sub getSlideNum()
    Set SlideDict = New Scripting.Dictionary
    SlideDict.Add "example1_SlideNum", 25
    SlideDict.Add "example2_SlideNum", 26
    SlideDict.Add "example3_SlideNum", 27

End Sub

Sub UsingTheDictionaryExample()
    getSlideNum
    Debug.Print SlideDict("example1_SlideNum")

    'You can concatenate a variable into your dictionary key as well
    Dim mySlideNum As Integer
    mySlideNum = 2
    Debug.Print SlideDict("example" & mySlideNum & "_SlideNum")

End Sub

Running that last subroutine will print out "25" and "26" in your immediate window pane.

Upvotes: 1

Related Questions