Try to get ListBox value from UserForm but I got this error: Run-time error 13: Type mismatch
-
Add a UserForm to the Power Point file.
-
Put a CommandButton and a ListBox on that UserForm.
-
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
-
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
-
Run Macro1 and then select msoShapeRectangle from ListBox which is part of the UserForm and press CommandButton.
-
This is the error message.
Run-time error 13: Type mismatch
-
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?
Answers
The error occurs because the myVariant
variable is declared as a Variant type, but the Type
parameter of the AddShape
method expects an MsoAutoShapeType enumeration value, not a Variant.
To resolve this error, you need to convert the string value obtained from the ListBox to the corresponding MsoAutoShapeType enumeration value before passing it to the AddShape
method.
Here's how you can modify your code to achieve this:
Public Sub Macro2()
ActivePresentation.Slides.Add 1, ppLayoutBlank
Dim myVariant As MsoAutoShapeType
Select Case UserForm1.ListBox1.Value
Case "msoShapePentagon"
myVariant = msoShapePentagon
Case "msoShapeRectangle"
myVariant = msoShapeRectangle
Case "msoShapeSmileyFace"
myVariant = msoShapeSmileyFace
Case Else
MsgBox "Invalid shape type"
Exit Sub
End Select
ActivePresentation.Slides(1).Shapes.AddShape Type:=myVariant, Left:=0, Top:=0, Width:=480, Height:=100
End Sub
In this modified code:
- The
myVariant
variable is declared as MsoAutoShapeType type. - We use a Select Case statement to determine the MsoAutoShapeType enumeration value based on the selected item in the ListBox.
- If the selected item in the ListBox is not one of the predefined shape types, a message box is displayed indicating that the shape type is invalid.
- Finally, the
AddShape
method is called with the determined MsoAutoShapeType value.