我试图弄清楚如果某个元素处于某个位置,如何从数组中删除它。我们还需要调整数组的大小。为了使示例更容易,让我们尝试删除数组中位置1中的任何颜色("绿色","蓝色","红色") 。
Sub Example()
Dim pos
colors = Array("Green", "Blue", "Red")
pos = 1
colors(pos).Delete 'obviously this doesn't work but what would the correct protocol be?
End Sub
答案 0 :(得分:4)
您可以将特定元素设置为单个空白,并将 TRIM()设置为不存在:
Sub DropFirstElement()
Colors = Array("Green", "Blue", "Red")
Colors(0) = " "
Mystring = Application.WorksheetFunction.Trim(Join(Colors, " "))
Colors = Split(Mystring, " ")
End Sub
注意:
我们使用工作表的 Trim()函数而不是VBA的 Trim()函数来删除多个连续的空格。
答案 1 :(得分:4)
您可以将数组中的值从 pos 开始,然后将ReDim移至新维度。
Sub Example()
Dim pos As Long, p As Long, vCOLOURs As Variant
vCOLOURs = Array("Green", "Blue", "Red", "Purple", "Pink")
For p = LBound(vCOLOURs) To UBound(vCOLOURs)
Debug.Print p & ": " & vCOLOURs(p)
Next p
'vCOLOURs is an array dimmed 0 to 4
pos = 3
'vCOLOURs(pos) is 'Purple'
For p = pos To UBound(vCOLOURs) - 1
vCOLOURs(p) = vCOLOURs(p + 1)
Next p
ReDim Preserve vCOLOURs(0 To (UBound(vCOLOURs) - 1))
For p = LBound(vCOLOURs) To UBound(vCOLOURs)
Debug.Print p & ": " & vCOLOURs(p)
Next p
End Sub
VBE立即窗口的结果(Ctrl + G)
example
0: Green
1: Blue
2: Red
3: Purple
4: Pink
0: Green
1: Blue
2: Red
3: Pink
请记住,用于将值放入变量数组的方法是创建一个从零开始的数组。第一个值为vCOLOURs(0)
,而不是vCOLOURs(1)
。
答案 2 :(得分:4)
您也可以使用Filter
(如果值是唯一的,就像在此示例中一样,任何匹配 Green 的字符串都会被删除)。
Colors = Array("Green", "Blue", "Red", "Yellow", "Pink")
Colors = Filter(Colors, Colors(0), False)