如何按条件移除VBA Collection中大于指定值的数值元素
VBA Collection移除指定条件元素的正确方法
不需要将Collection内容粘贴到Excel中再删除,直接操作Collection即可,但你提供的代码存在几个问题:
- 使用
For Each遍历Collection时直接删除元素会导致遍历出错(枚举器失效) XY.Item的写法错误,应使用循环变量Item,且Remove方法需要指定元素的索引或键- 代码缺少
End If,语法不完整
正确方法1:倒序遍历索引删除
从Collection的最后一个元素往前遍历,这样元素移除后不会影响未遍历的元素索引:
Dim XY As New Collection Dim threshold As Double Dim i As Integer ' 此处可替换为你的实际数据填充逻辑 XY.Add 50 XY.Add 120 XY.Add 80 XY.Add 150 ' 计算阈值 threshold = Cells(11, 2).Value + Cells(12, 2).Value ' 倒序遍历删除符合条件的元素 For i = XY.Count To 1 Step -1 If XY(i) > threshold Then XY.Remove i End If Next i
正确方法2:新建Collection筛选元素
这种方法更安全,不会出现索引错位问题,通过新建集合存储符合要求的元素,再替换原集合:
Dim XY As New Collection Dim filteredXY As New Collection Dim threshold As Double Dim item As Variant ' 此处可替换为你的实际数据填充逻辑 XY.Add 50 XY.Add 120 XY.Add 80 XY.Add 150 ' 计算阈值 threshold = Cells(11, 2).Value + Cells(12, 2).Value ' 筛选并保留符合条件的元素 For Each item In XY If item <= threshold Then filteredXY.Add item End If Next item ' 用筛选后的集合替换原集合 Set XY = filteredXY
内容的提问来源于stack exchange,提问作者D89
相关产品推荐
相关产品推荐

