假设我在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

最佳答案

如果您不介意将所有字符串值都放在末尾

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

09-05 04:38