在VBA Word 2010中按名称删除CommandButtons [英] Deleting CommandButtons by name in VBA Word 2010
问题描述
在一个单词模板中,我有两个命令按钮
In a word template, I have two command buttons namely
-
[添加部分] ,名为"CommandButton1"
[Add section] which is named "CommandButton1"
[完成] -名为"CommandButton2"
[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
该代码是我在网上找到的代码段的组合.我只添加了"CommandButton1"用于测试目的,并且打算在此方法下也添加对CommandButton2的检查.
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.
在执行代码时,它成功删除了CommandButton2,并给我一个错误:"无法在水平线上访问对象",而没有删除CommandButton1.
On executing the code it successfully deletes CommandButton2 and gives me an error "Objected cannot be accessed on a horizontal line" without deleting CommandButton1.
我尝试弄乱计数到1步骤-1"部分(我不知道它们的含义),但这都导致了同一件事.
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.
推荐答案
for ... next
循环是从结尾(ThisDocument.InlineShapes.Count)到数组的开头完成的,以确保遍历所有需要的项要删除.
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.
例如,如果数组有3个项目,则从第一个项目到最后一个项目:
For instance, going from first to last item, if your array has 3 items:
- 对象(1)
- 对象(2)
- 对象(3)
通过删除第一项,将对数组重新排序,并且Object(2)将获得索引1,Object(3)将获得索引2.使用for ... next
可能会导致问题,因为总数为数组中的项目与开始循环时的项目不同.
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.
在这种情况下,我宁愿使用do while ... 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
这篇关于在VBA Word 2010中按名称删除CommandButtons的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!