Deleting CommandButtons by name in VBA Word 2010

微笑、不失礼 提交于 2019-12-13 18:24:54

问题


In a word template, I have two command buttons namely

  1. [Add section] which is named "CommandButton1"

  2. [Done] - which is named "CommandButton2"

I need both buttons to be deleted at the click of [Done]

Here's my code so far

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

The code is a combination of snippets I found online. I had only added "CommandButton1" for testing purpose and was planning to add a check for CommandButton2 as well if this works.

On executing the code it successfully deletes CommandButton2 and gives me an error "Objected cannot be accessed on a horizontal line" without deleting CommandButton1.

I tried messing around with the "count to 1 Step -1" part (I don't know what they imply), but it all results in the same thing.


回答1:


The for ... next loop is done from the end (ThisDocument.InlineShapes.Count) to the start of the array to be sure to go through all items that need to be deleted.

For instance, going from first to last item, if your array has 3 items:

  • Object(1)
  • Object(2)
  • Object(3)

By deleting the first item, the array would be re-ordered, and Object(2) will get index 1 and Object(3) will get index 2. Using for ... next could lead you to an issue as total number of items in your array is not the same than when you started your loop.

I'd rather use a do while ... loop in this case:

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


来源:https://stackoverflow.com/questions/28902582/deleting-commandbuttons-by-name-in-vba-word-2010

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!