根据标题删除按钮

问题描述 投票:0回答:1

使用Windows 10,Excel 2016.代码位于模块中。

该代码在2015年工作。现在它抛出错误。

代码尝试通过其标题找到按钮以将其删除。每个工作表只有一个按钮。

DeleteShapesByCaption "Create a new Schedule of Values tab", wSht

Sub DeleteShapesByCaption( _
ByVal Caption As String, _
Optional ByVal WS As Worksheet = Nothing)

Dim Shp As Shape, i as long

If WS Is Nothing Then Set WS = ActiveSheet

WS.Unprotect Protect_Password
For i = WS.Shapes.Count To 1 Step -1
    Set Shp = WS.Shapes(i)
    Select Case Shp.Type
    Case msoOLEControlObject
        If Shp.OLEFormat.Object.Object.Caption = Caption Then
            Shp.Delete  'This is where the error occurs
            Exit For
        End If
    Case msoFormControl
        'May be a button
        If Shp.OLEFormat.Object.Caption = Caption Then Shp.Delete
    End Select
Next i
WS.Protect Protect_Password
End Sub

错误发生在第一次出现的Shp.Delete时。

RTE 404对象必需

要么

RTE -2147024809(80070057)指定的值超出范围

语境:

工作簿有一个工作表,它是一个模板。填充模板后,将其复制到第1个月。完成月份1表单后,单击create_a_new_sheet_button以创建第2个月的新工作表,并且应该从月份1工作表中删除create_a_new_sheet_button。每张纸只有一个按钮。

我使用debug.print来确认活动表是上个月的表。

我修改了单元格公式以反映更改,但我不认为这些更改与错误相关,因为现在2015年原始工作簿会产生错误。

代码在创建月份1表时按预期执行。唯一的区别是create_a_new_sheet按钮不会从模板页面中删除。

我可以更改标题并禁用按钮作为无错误的解决方法,但最好删除它。

excel vba button shapes
1个回答
0
投票

删除具有指定标题的按钮。 ActiveX控件。

Sub DeleteBtn()
    Dim btn As OLEObject, s As String

    s = "ButtonName"
    For Each btn In ActiveSheet.OLEObjects
        If TypeName(btn.Object) = "CommandButton" Then
            If btn.Object.Caption = s Then
                btn.Delete
            End If
        End If
    Next
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.