vba 根据VBA的值从列表框中删除项目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23215035/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 02:50:59  来源:igfitidea点击:

Removing items from listbox according to their values VBA

excelvbalistbox

提问by user1040563

I'm trying to delete all the items in a user form list-box except for specific values

我正在尝试删除用户表单列表框中的所有项目,但特定值除外

lets say I want to delete everything in my list-box except "Cat" and "Dog"

假设我想删除列表框中除“猫”和“狗”之外的所有内容

I wrote:

我写:

For i = 0 To ListBox2.ListCount - 1
    If ListBox2.List(i) <> "Cat" or ListBox2.List(i) <> "Dog" Then
        ListBox2.RemoveItem i
    End If
Next 

For some reason it doesn't work, I tried to find a solution but I couldn't. What is wrong here?

由于某种原因它不起作用,我试图找到一个解决方案,但我不能。这里有什么问题?

回答by Dmitry Pavliv

Use backwards loop:

使用反向循环:

For i = ListBox2.ListCount - 1 To 0 Step -1
    If ListBox2.List(i) <> "Cat" AND ListBox2.List(i) <> "Dog" Then
        ListBox2.RemoveItem i
    End If
Next 

and also change ORto ANDin your IFstatement

并在您的声明中更改ORANDIF