连接两个数组
作为 Scott Craner 提出的正确可行方法的替代方法
创建第三个数组,它的大小为两个数组组合的大小,
然后循环遍历每个数组,逐个添加项目。
...我演示了一种方法
-
仅通过循环插入第二个数组的元素
到一个主数组中,而
-
主数组仅由一个一个内衬通过
Application.Index()重组。
由于此函数会将结果更改为从 1 开始的数组,因此我将数组重新调整为从零开始的数组。此外,我在 VBE 的即时窗口中添加了一个可选显示,结果为 2|4|5|3|7|6 值:
第一步:使用与 OP 中相同的数组值的简单演示(插入 1 个元素)
Sub SimpleDemo()
'[0]declare and assign zero-based 1-dimensioned arrays
Dim main, newTop
main = Array(4, 5, 3, 7, 6)
newTop = Array(2) ' only one element in a first step
'[1]transform main array by inserting(/i.e. repeating) "another" 1st element
main = Application.Index(main, Array(1, 1, 2, 3, 4, 5)) ' changes to 1-based 1-dim array
ReDim Preserve main(0 To UBound(main) - 1) ' back to zero-based 1-dim array
'[2]overwrite new first element by the 1st(only) element of newTop
main(0) = newTop(0)
'[3](optional) display in VBE's Immediate Window: main(0 To 5) ~> 2|4|5|3|7|6
Debug.Print "main(" & LBound(main) & " To " & UBound(main) & ") ~> " & _
Join(main, "|")
End Sub
第二步:使用AddElem 过程的更通用的方法
上面的演示只插入了一个一个元素。因此我编写了一个AddElem 过程和一个帮助函数addedElems() 以允许插入更多元素。假设所有 1-dim 数组都是从零开始的,就像在原始帖子中一样;顺便说一句,可以很容易地适应:-)
Sub AddElem(main, newTop)
' Purp. : add/insert other array element(s) on top of zero-based main array
' Author: https://stackoverflow.com/users/6460297/t-m
' Date : 2020-02-05
' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
' a)insert newTop element(s) on top of main array
main = Application.Index(main, addedElems(main, newTop)) ' changes temporarily to 1-based mainay!
' b)make main array zero-based again (optional)
ReDim Preserve main(0 To UBound(main) - 1)
' c)overwrite inserted starting element(s) by the newTop element(s)
Dim i&: For i = 0 To UBound(newTop): main(i) = newTop(i): Next i
End Sub
帮助功能addedElems()
Function addedElems(main, newTop) As Variant()
'Note : help function called by AddElem()
'Purp.: return ordinal element counters of combined arrays
Dim i&, n&: n = UBound(main) + UBound(newTop) + 1
ReDim tmp(0 To n)
For i = 0 To UBound(newTop): tmp(i) = i: Next i
For i = i To n: tmp(i) = i - UBound(newTop): Next i
addedElems = tmp ' return combined elem counters, e.g. Array(1,2, 1,2,3,4,5)
End Function
调用示例
我稍微改变了 OP 的第二个数组的值(Array(2) ~>Array(20,21) 来演示更多元素的插入,因此
产生一个合并的Array(20,21,2,4,5,3,7,6)。
Sub ExampleCall()
'[0]declare and assign zero-based 1-dimensional arrays
Dim main, newTop
main = Array(4, 5, 3, 7, 6)
newTop = Array(20, 21)
'[1]Add/Insert newTop on top of main array
AddElem main:=main, newTop:=newTop ' or simply: AddElem main, newTop
'[2](optional) display in VBE's Immediate Window: ~~> main(0 To 6) ...20|21|4|5|3|7|6
Debug.Print "main(" & LBound(main) & " To " & UBound(main) & ") ..." & _
Join(main, "|")
End Sub
相关链接
同样,您可以在Insert first column in datafield array without loops or API calls 研究应用于二维数组的Application.Index() 函数的一些特性