尝试从 UserForm 获取 ListBox 值,但出现此错误:运行时错误 13:类型不匹配

问题描述 投票:0回答:1
  1. UserForm 添加到 Power Point 文件。

  2. UserForm 上放置一个 CommandButtonListBox

  3. 将以下代码放在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. 将以下代码放在Power Point文件的Module1下。

      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. 运行Macro1,然后从ListBox(属于UserForm的一部分)中选择msoShapeRectangle,然后按CommandButton

  6. 这是错误信息。

     Run-time error 13: Type mismatch
    
  7. 这是错误行

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

那么我该如何解决这个错误呢?

vba types enums powerpoint ms-office
1个回答
0
投票

"msoShapePentagon"
String
)与
msoShapePentagon
(对应值为 51 的 enum 成员)不同。

一个选项是将

String
表示形式转换为枚举中的等价形式的函数:

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

请注意,您需要将此函数传递给

String
,而不是
Variant

© www.soinside.com 2019 - 2024. All rights reserved.