vba 如何在数组中的某个索引处插入一个新值并将所有内容向下移动一个索引?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42339959/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to insert a new value at certain index in an array and shift everything down by one index?
提问by Stupid_Intern
let's say if I have this array in vba
假设我在 vba 中有这个数组
a(0) = 1
a(1) = f
a(2) = g
a(3) = 4
.
..
..
a(k) = a
and I want to insert a new value at (0) and shift every value down by one index like this
我想在 (0) 处插入一个新值并将每个值向下移动一个像这样的索引
a(0) = newVal
a(1) = 1
a(2) = f
a(3) = g
a(4) = 4
.
..
..
a(k+1) = a
is there a short hand code to do this if not what's the fastest way to do this?
如果没有,是否有简写代码可以做到这一点,最快的方法是什么?
I can do this with simple for loop but I was wondering if there is more efficient way?
我可以用简单的 for 循环来做到这一点,但我想知道是否有更有效的方法?
Example this is what I can come up with
例子这是我能想出的
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
回答by Shai Rado
The code below will add a value (through variable NewVal
) to an existing populated array. You can use the code to add an element in the middle of the array or the end (if you need to), you just need to modify the value of ElemId
.
下面的代码将向NewVal
现有的填充数组添加一个值(通过变量)。您可以使用代码在数组的中间或末尾添加元素(如果需要),您只需要修改ElemId
.
Note: If you are reading the array a
values from a worksheet's range, then the code can be simplified.
注意:如果您a
从工作表的范围中读取数组值,则可以简化代码。
Code
代码
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
回答by user3598756
if you don't mind having all string values at the end
如果你不介意在最后有所有的字符串值
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