最好不使用循环,是否可以用另外两个数组的内容(我们称之为A
)填充一个空数组的内容(我们称之为C
)和B
?
Dim A() As Double
Dim B() As Double
ReDim A(1 To 100,1 To 1)
ReDim B(1 To 100,1 To 1)
' fill A and B with stuff...
Dim C As Double
' I now want "A" to form the first column and "B" to form the second column of array C
C(1 To 100, 1) = A(1 To 100, 1) ' Compile error at '=': Expected end of statement
C(1 To 100, 2) = B(1 To 100, 1) ' Compile error at '=': Expected end of statement
我做错了什么?
最佳答案
Preferably without using loops, is it possible to fill the contents of an empty array
就像我在评论中提到的,可以将两个数组组合成第三个数组不使用循环。
执行此操作的关键是不要使用 Double
作为数组类型,而是使用 Variant
。请参阅此示例。
Option Explicit
Sub Sample()
Dim A(1 To 2) As Variant
Dim B(1 To 2) As Variant
Dim C As Variant
Dim Ub_A As Long, Ub_B As Long, i As Long
Dim sA As String, sB As String, sAB As String
'~~> Assign sample data to array A and B
A(1) = 1: A(2) = 2: B(1) = 3: B(2) = 4
Ub_A = UBound(A): Ub_B = UBound(B)
sA = "{" & Join(A, ",") & "},"
sB = "{" & Rept("0,", Ub_A) & Join(B, ",") & "},"
sAB = "{" & Rept("1,", Ub_A) & Rept("2,", Ub_B)
sAB = Left(sAB, Len(sAB) - 1) & "},"
'~~> Construct your C Array
C = Evaluate("Choose(" & sAB & sA & sB & ")")
'~~> For testing purpose only to check the elements of C Array
For i = LBound(C) To UBound(C)
Debug.Print ">>"; C(i)
Next i
End Sub
Private Function Rept(s As String, j As Long) As String
Rept = Replace(Space(j), " ", s)
End Function
屏幕截图
关于vba - 如何用另一个数组的内容填充数组的列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22775994/