目录
一、插入按钮并编写代码
二、以下有三段代码
(1)一开始可以选择多个节点,点击按钮后可删除所有选中节点。第一次删除后,每点击一个节点都会进行自动删除,不需要再点击按钮。
Sub OnClick(Byval Item)
Dim TV,checkcount,i,count,key
Set TV=ScreenItems("TV")
count=TV.Nodes.count
checkcount=0
For i = 1 To count
If TV.Nodes.item(i).checked=True Then
checkcount=checkcount+1
End If
Next
Do While checkcount>0
For i = 1 To TV.nodes.count
If i=TV.nodes.count+1 Then
i=1
End If
If TV.nodes.item(i).checked=True Then
key=TV.nodes.item(i).key
TV.nodes.remove(key)
checkcount=checkcount-1
End If
Next
Loop
End Sub
(2) 选择多个节点,点击按钮后可删除所有选中节点。每次都可如此操作。
Sub OnClick(Byval Item)
Dim TV,checkcount,i,count,key
Set TV=ScreenItems("TV")
count=TV.Nodes.count
checkcount=0
For i = 1 To count
If TV.Nodes.item(i).checked=True Then
checkcount=checkcount+1
End If
Next
i=0
Do While checkcount>0
i=i+1
If i=TV.nodes.count+1 Then
i=1
End If
If TV.nodes.item(i).checked=True Then
key=TV.nodes.item(i).key
TV.nodes.remove(key)
checkcount=checkcount-1
End If
Loop
End Sub
下面的代码和上面的效果一致
Sub OnClick(Byval Item)
Dim TV,checkcount,i,count,key
Set TV=ScreenItems("TV")
count=TV.Nodes.count
checkcount=0
For i = 1 To count
If TV.Nodes.item(i).checked=True Then
checkcount=checkcount+1
End If
Next
i=0
Do While checkcount>0
i=i+1
If TV.nodes.item(i).checked=True Then
key=TV.nodes.item(i).key
TV.nodes.remove(key)
checkcount=checkcount-1
i=i-1
End If
Loop
End Sub
三、关键语句分析
(1)若没有下面这一段语句或者改为 If i=count+1 Then 时,每次运行到 If TV.nodes.item(i).checked=True Then 时都会提示超出下标范围。
If i=TV.nodes.count+1 Then
i=1
End If
如图所示,i(5) i(6) i(7)被勾选了,当i循环到i=5时,删除FT101这个节点。此时,TV.nodes.count=19,checkcount=2。因为删除了FT101这个节点,所以i(5)变成了FT201,但是下一次循环是从i=6开始了,所以FT201并没能删除。
由此可知,当连续勾选时,会一隔一进行删除,由于checkcount在一隔一删除时不会变为0。所以当i=TV.nodes.count+1时,i变为1,重新进行一轮删除。这也是不能用count代替TV.nodes.count的原因。
或者如第三段代码所示,当进行删除时,让i减去1。
If TV.nodes.item(i).checked=True Then
key=TV.nodes.item(i).key
TV.nodes.remove(key)
checkcount=checkcount-1
i=i-1
End If
(2)为何第一段程序,会出现如此情况?
因为使用了For循环,只要i没有增加到TV.nodes.count,那么循环会一直继续下去。这个时候checkcount已经为0了,所以才会出现之后没选中一个节点,就会删除一个节点的情况。
这时候需要加一个跳出循环的语句。
If TV.nodes.item(i).checked=True Then
key=TV.nodes.item(i).key
TV.nodes.remove(key)
checkcount=checkcount-1
End If
If checkcount=0 Then
Exit For
End If