Excel vba形成内部名称/类型

时间:2017-10-25 15:54:05

标签: excel vba excel-vba

我需要删除除命令按钮以外的所有形状。或者只删除椭圆,直线和绘制的线条。

Sub deleteShapes()

Dim shp As Shape
For Each shp In ActiveSheet.Shapes

  shp.Delete
Next shp

End Sub

this answer中杰米·布尔删除了形状:

If Not (Shp.Type = msoOLEControlObject Or Shp.Type = msoFormControl) Then Shp.Delete

但是如何获得我的命令按钮类型?还是其他对象类型?我试过了

Sub testShapes()
    Dim shp As Shape

For Each shp In ActiveSheet.Shapes
    MsgBox (shp.Type)
Next shp

End Sub

但它只给出数字:9,5,1,12。我不知道哪个数字是哪个形状。有没有办法获得像msoOLEControlObject这样的内部名称,或者至少确保数字1真的是命令按钮?

2 个答案:

答案 0 :(得分:2)

类型列表在这里:https://msdn.microsoft.com/en-us/VBA/Office-Shared-VBA/articles/msoshapetype-enumeration-office 所有值都在VBA中定义为常量,因此您可以编写

if not shp.Type = msoOLEControlObject then
    shp.Delete
end if

获取更多关于您拥有何种控制的信息:

Dim sh As Shape
For Each sh In Activesheet.Shapes
    Debug.Print sh.Name, sh.Type

    If sh.Type = msoFormControl Then
        Debug.Print "  msoFormControl:" & sh.FormControlType
    End If

    If sh.Type = msoOLEControlObject Then
        Debug.Print "  msoOLEControlObject: " & TypeName(sh.OLEFormat.Object.Object)
    End If
Next sh

FormControlType显示在这里:https://msdn.microsoft.com/en-us/vba/excel-vba/articles/xlformcontrol-enumeration-excel - 所有也被定义为VBA常量

答案 1 :(得分:1)

如果您使用形状的默认名称,那么对于表单按钮:

Sub poiuyt()
    Dim shp As Shape

    For Each shp In ActiveSheet.Shapes
        If Left(shp.Name, 6) = "Button" Then
        Else
            shp.Delete
        End If
    Next shp
End Sub

如果按钮是activex,则:

Sub trewq()
    Dim shp As Shape

    For Each shp In ActiveSheet.Shapes
        If Left(shp.Name, 13) = "CommandButton" Then
        Else
            shp.Delete
        End If
    Next shp

End Sub

仅当名称属于默认类型时,此方法才有效。