Search code examples
vbatypesenumspowerpointms-office

Try to get ListBox value from UserForm but I got this error: Run-time error 13: Type mismatch


  1. Add a UserForm to the Power Point file.

  2. Put a CommandButton and a ListBox on that UserForm.

  3. Put the following codes under the UserForm.

     Public Sub UserForm_Initialize()
         UserForm1.ListBox1.AddItem "msoShapePentagon"
         UserForm1.ListBox1.AddItem "msoShapeRectangle"
         UserForm1.ListBox1.AddItem "msoShapeSmileyFace"
     End Sub
    

    ''''''''''''''''''''''''''''''''

     Public Sub CommandButton1_Click()
         MsgBox UserForm1.ListBox1.Value
         UserForm1.Hide
         Call Macro2
     End Sub
    
  4. Put the following codes under the Module1 of Power Point file.

      Public Sub Macro1()
          UserForm1.Show
      End Sub
    

    ''''''''''''''''''''''''''''''''

     Public Sub Macro2()
         ActivePresentation.Slides.Add 1, ppLayoutBlank
    
         Dim myVariant As Variant
         myVariant = UserForm1.ListBox1.Value
         MsgBox myVariant
    
         'This line is okey
         'ActivePresentation.Slides(1).Shapes.AddShape Type:=msoShapeRectangle, Left:=0, Top:=0, Width:=480, Height:=100
    
         'This line gives an error
         ActivePresentation.Slides(1).Shapes.AddShape Type:=myVariant, Left:=0, Top:=0, Width:=480, Height:=100
      End Sub
    
  5. Run Macro1 and then select msoShapeRectangle from ListBox which is part of the UserForm and press CommandButton.

  6. This is the error message.

     Run-time error 13: Type mismatch
    
  7. This is the error line

     ActivePresentation.Slides(1).Shapes.AddShape Type:=myVariant, Left:=0, Top:=0, Width:=480, Height:=100
    

So how can I solve that error?


Solution

  • "msoShapePentagon", a String, is not the same as msoShapePentagon, a member of an enum with a corresponding value of 51.

    One option is a function to convert the String representation to the equivalent from the enum:

    Private Function ShapeType(s As String) As MsoAutoShapeType
        Dim result As MsoAutoShapeType
        
        Select Case s
            Case "msoShapePentagon"
                result = msoShapePentagon
            Case "msoShapeRectangle"
                result = msoShapeRectangle
            Case "msoShapeSmileyFace"
                result = msoShapeSmileyFace
        End Select
        
        ShapeType = result
    End Function
    

    Note that you need to pass this function a String, not a Variant.