vba - 如何用另一个数组的内容填充数组的列?

标签 vba excel-2010

最好不使用循环,是否可以用另外两个数组的内容(我们称之为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

屏幕截图

enter image description here

关于vba - 如何用另一个数组的内容填充数组的列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22775994/

相关文章:

vba - Excel VBA将字符串日期转换为真实日期

vba - 在 Excel 2010 中调用 URL 而不打开网页

excel - 索引匹配 : String in cell to mappings

vba - 将excel文本导出为图像文件

vba - PowerPoint VBA - 循环所有幻灯片、所有形状、查找图表、将数据标签颜色设置为黑色

vba - 如何在不打开的情况下保存用vba编码的excel文件?

vba - 来自网页的消息。 : 1行出现堆栈溢出

excel - 如何在 Excel 中绘制 3D 线框?

vba - 为什么 VBA 在 ActiveWorkbook.SaveAs 上创建一个文件夹

vba - 计算VBA中不同单元格的数量