按位置移除数组中的元素
我想弄清楚如果从一个数组中删除一个元素,如果它在某个位置。 我们还需要调整数组的大小。 为了让示例更容易,我们尝试删除arrays中位置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
您可以将特定元素设置为单个空白,并将TRIM()设置为不存在:
Sub DropFirstElement() Colors = Array("Green", "Blue", "Red") Colors(0) = " " Mystring = Application.WorksheetFunction.Trim(Join(Colors, " ")) Colors = Split(Mystring, " ") End Sub
注意:
我们使用工作表的Trim()函数而不是VBA的Trim()函数来删除多个连续的空格。
您可以将数组中的值从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
请记住,用于将值放入您的variables数组中的方法是创build一个从零开始的数组。 第一个值是vCOLOURs(0)
,而不是vCOLOURs(1)
。
你也可以使用Filter
(如果这个值是唯一的,在这个例子中,任何匹配绿色的string都被删除)。
Colors = Array("Green", "Blue", "Red", "Yellow", "Pink") Colors = Filter(Colors, Colors(0), False)