如何在数组中的某个索引处插入新值并将所有内容向下移动一个索引?

时间:2017-02-20 08:48:19

标签: arrays vba

让我们说如果我在vba中有这个数组

a(0) = 1
a(1) = f
a(2) = g
a(3) = 4
.
..
..
a(k) = a

我希望在(0)处插入一个新值,并将每个值向下移动一个索引,如此

a(0) = newVal
a(1) = 1
a(2) = f
a(3) = g
a(4) = 4
.
..
..
a(k+1) = a

是否有一个简短的手动代码来执行此操作,如果不是最快的方法是什么?

我可以通过简单的for循环来做到这一点,但我想知道是否有更有效的方法?

这是我能想到的例子

Dim temp()

Redim Preserve temp(0)
temp(0) = "newVal"

For i= lbound(a) + 1 to ubound(a) + 1
     redim preserve temp(i)
     temp(i) = a(i-1)
Next i

2 个答案:

答案 0 :(得分:3)

下面的代码会将值(通过变量NewVal)添加到现有的填充数组中。您可以使用代码在数组中间或末尾添加元素(如果需要),只需修改ElemId的值。

注意:如果您正在从工作表的范围中读取数组a值,则可以简化代码。

代码

Option Explicit

Sub AddElemToArray()

Dim a() As Variant
Dim ElemId  As Long, i As Long
Dim NewVal As Variant

ReDim a(0 To 4) '<-- modify th value 4 to your array size
NewVal = "Test"

a(0) = 1
a(1) = "f"
a(2) = "g"
a(3) = 4
a(4) = "a"

ReDim Preserve a(0 To UBound(a) + 1)

ElemId = 2 '<-- which element ID inside the array to modify

For i = UBound(a) To ElemId + 1 Step -1
    a(i) = a(i - 1)
Next i
a(ElemId) = NewVal

End Sub

答案 1 :(得分:2)

如果你不介意最后有所有的字符串值

Dim newVal As Variant
Dim tempVar As Variant

newVal = "newValue"

tempVar = newVal & "|"  & Join(a, "|")
ReDim a(0 To k + 1) As Variant
tempVar = Split(tempVar, "|")
For i = 0 To k + 1
    a(i) = tempVar(i)
Next