vba multiD数组到范围

时间:2017-03-24 14:30:03

标签: arrays excel vba excel-vba multidimensional-array

我遇到了将4D数组写入Excel中的范围的问题。

My Array看起来像这样:

Xb

最后数组中只有2个“项目”,但为了理解我展示了其中2个。

我尝试使用转置,但我没有访问子项目

varArray(0)
- varArray(0)(0) "test01"
- varArray(0)(1) "test02"
- varArray(0)(2) "test03"
- varArray(0)(3) "test04"

varArray(1)
- varArray(1)(0) "test11"
- varArray(1)(1) "test12"
- varArray(1)(2) "test13"
- varArray(1)(3) "test14"

不起作用:S

输出应如下所示(写入范围):

Range("A" & CellIndex) = Application.Transpose(varArray(0,1))

有人可以帮我吗?

4 个答案:

答案 0 :(得分:1)

你想要这样的东西:

选项明确

Public Sub TestMe()

    Dim varArray            As Variant
    Dim lCounter            As Long
    Dim lCounter2           As Long
    Dim rngCell             As Range

    varArray = Array(Array(1, 2, 3, 4), Array(11, 12, 13, 14))
    Set rngCell = Cells(1, 1)

    For lCounter = LBound(varArray) To UBound(varArray)
        For lCounter2 = LBound(varArray(lCounter)) To UBound(varArray(lCounter))

            Debug.Print varArray(lCounter)(lCounter2)

            rngCell = varArray(lCounter)(lCounter2)
            Set rngCell = rngCell.Offset(0, 1)

        Next lCounter2
        Debug.Print "-----------"
        Set rngCell = Cells(rngCell.Row + 1, 1)

    Next lCounter

End Sub

立即窗口中的结果是:

 1 
 2 
 3 
 4 
-----------
 11 
 12 
 13 
 14 
-----------

通过此输出,您可以轻松找到所需的输出。

答案 1 :(得分:1)

您可以使用Sub CreateArray() Dim varArray As Variant varArray = Array(Array(1, 2, 3, 4), Array(11, 12, 13, 14)) For i = 0 To 1 ThisWorkbook.Worksheets("Sheet1").Range("A1:D1").Offset(i, 0).Value = Application.Transpose(Application.Transpose(varArray(i))) Next i End Sub 两次。这将输出到A:D列中的工作表

-d @-

答案 2 :(得分:1)

尝试:

Dim varArray(0 To 1, 0 To 3) As String
    varArray(0, 0) = "test01"
    varArray(0, 1) = "test02"
    varArray(0, 2) = "test03"
    varArray(0, 3) = "test04"
    varArray(1, 0) = "test11"
    varArray(1, 1) = "test12"
    varArray(1, 2) = "test13"
    varArray(1, 3) = "test14"
Range("A1:D2") = varArray()
Range("F1:G4") = Application.Transpose(varArray())

我认为您想要的输出只是您的数组,而不是您的转置数组。但是我把两个输出放在代码上。随意改变地址......

答案 3 :(得分:1)

您正尝试在数组中转置单个项目:

Application.Transpose(varArray(0,1))

此外,此数组未以此方式编入索引。您可以拥有varArray(0)(1),但拥有varArray(0,1)

试试这个:

Dim x as Long
For x = LBound(varArray) To UBound(varArray)
    Range("A1").Resize(1, UBound(varArray(x)) + 1).Offset(x) = Application.Transpose(Application.Transpose(varArray(x)))

Next