在VBA Word 2010中按名称删除CommandButtons

时间:2015-03-06 15:57:14

标签: vba ms-word word-vba

在单词模板中,我有两个命令按钮,即

  1. [添加部分] ,名为“CommandButton1”

  2. [完成] - 名为“CommandButton2”

  3. 我需要点击[完成]

    删除这两个按钮

    到目前为止,这是我的代码

    Private Sub CommandButton2_Click()
    
        Dim i As Integer
    
        For i = ThisDocument.InlineShapes.Count To 1 Step -1
    
          With ThisDocument.InlineShapes(i)
              If .OLEFormat.Object.Name = "CommandButton1" Then
                  .Delete
              End If
           End With
       Next
    
    End Sub
    

    代码是我在网上找到的片段组合。我只是添加了“CommandButton1”用于测试目的,并且计划为CommandButton2添加一个检查,如果这样做的话。

    在执行代码时,它成功删除了CommandButton2,并在不删除CommandButton1的情况下向我提供了错误“ Objected无法在水平线上访问”。

    我试着搞乱“数到1步-1”部分(我不知道他们暗示了什么),但这一切都导致了同样的事情。

1 个答案:

答案 0 :(得分:1)

for ... next循环从最后(ThisDocument.InlineShapes.Count)到数组的开头,以确保遍历所有需要删除的项目。

例如,如果您的数组有3个项目,则从第一个项目到最后一个项目:

  • 对象(1)
  • 对象(2)
  • 对象(3)

通过删除第一个项目,数组将被重新排序,Object(2)将获得索引1而Object(3)将获得索引2.使用for ... next可能会导致您出现问题数组中的项目数与启动循环时的项目数不同。

在这种情况下,我宁愿使用do while ... loop

Private Sub CommandButton2_Click()

    On Error Resume Next
    Err.Clear

    Dim i As Integer
    i = ThisDocument.InlineShapes.Count
    Do While (i > 0)
        If ThisDocument.InlineShapes(i).OLEFormat.ClassType = "Forms.CommandButton.1" Then

            If ThisDocument.InlineShapes(i).OLEFormat.Object.Name = "CommandButton1" _
            Or ThisDocument.InlineShapes(i).OLEFormat.Object.Name = "CommandButton2" Then

                If Err.Number = 0 Then
                    ThisDocument.InlineShapes(i).Delete
                End If
                Err.Clear

            End If

        End If
        i = i - 1
    Loop
End Sub