1

昨天我问了你们一个非常模糊的问题。我现在已经设法隔离了这个问题,但显然没有解决我在这里写的问题。

我的问题是为变量分配矩阵的值/内容(或变体的变体)。不确定这是否是多余的,但我想在我的电子表格中包含以下内容:

   A   B   C   D   E   F
1  a   b   c   d      
2  e   f   g   h
3  aa  bb  cc  dd
4  ee  ff  gg  hh

这是代码:

Public Sub Test()

    Dim sub_data As Variant
    Dim sheet_name As String
    Dim str As String
    Dim rng As Range

    sheet_name = "Sheet1"
    Set rng = Sheets(sheet_name).Range("A1")
    Worksheets(sheet_name).Cells.ClearContents

    On Error Resume Next

    str = "A" & CStr(print_row)

    ReDim sub_data(0 To 1, 0 To 1, 0 To 3)

    sub_data(0, 0, 0) = "a"
    sub_data(0, 0, 1) = "b"
    sub_data(0, 0, 2) = "c"
    sub_data(0, 0, 3) = "d"

    sub_data(0, 1, 0) = "e"
    sub_data(0, 1, 1) = "f"
    sub_data(0, 1, 2) = "g"
    sub_data(0, 1, 3) = "h"

    sub_data(1, 0, 0) = "aa"
    sub_data(1, 0, 1) = "bb"
    sub_data(1, 0, 2) = "cc"
    sub_data(1, 0, 3) = "dd"

    sub_data(1, 1, 0) = "ee"
    sub_data(1, 1, 1) = "ff"
    sub_data(1, 1, 2) = "gg"
    sub_data(1, 1, 3) = "hh"

    Call PrintArray(sub_data, str)

End Sub

Public Sub PrintArray(Data As Variant, Cl As String)

    Dim ubnd_1, ubnd_2 As Integer
    Dim sub_data As Variant

    ubnd_1 = UBound(Data, 2)
    ubnd_2 = UBound(Data, 3)

    sub_data = Data(0) 'THIS LINE WON'T WORK. HOW TO ASSIGN CORRECTLY?

    'here I want to print the content of the Data-variable onto the sheet
    Range(Cl).Resize(ubnd_2 + 1, ubnd_1 + 1) = Application.Transpose(sub_data)
End Sub
4

1 回答 1

1

您不需要 3D 阵列。我已将您的 3D 更改为 2D,因为您的示例只需要二维。电子表格无论如何都是 2D 的,所以转置 3D 数组听起来是不可能的。

最简单的方法

Public Sub PrintArray(Data As Variant)
    Range("A10").Resize(UBound(Data, 1), UBound(Data, 2)) = Data
End Sub

但是您必须确保更改矩阵/数组的尺寸

Option Explicit

Public Sub Test()

    Sheets(1).Cells.ClearContents

    ReDim sub_data(1 To 4, 1 To 4)

    sub_data(1, 1) = "a"
    sub_data(1, 2) = "b"
    sub_data(1, 3) = "c"
    sub_data(1, 4) = "d"

    sub_data(2, 1) = "e"
    sub_data(2, 2) = "f"
    sub_data(2, 3) = "g"
    sub_data(2, 4) = "h"

    sub_data(3, 1) = "aa"
    sub_data(3, 2) = "bb"
    sub_data(3, 3) = "cc"
    sub_data(3, 4) = "dd"

    sub_data(4, 1) = "ee"
    sub_data(4, 2) = "ff"
    sub_data(4, 3) = "gg"
    sub_data(4, 4) = "hh"

    Call PrintArray(sub_data)

End Sub

Public Sub PrintArray(Data As Variant)

    Range("A1:A" & UBound(Data, 2)) = WorksheetFunction.Transpose(WorksheetFunction.Index(Data, 1, 0))
    Range("B1:B" & UBound(Data, 2)) = WorksheetFunction.Transpose(WorksheetFunction.Index(Data, 2, 0))
    Range("C1:C" & UBound(Data, 2)) = WorksheetFunction.Transpose(WorksheetFunction.Index(Data, 3, 0))
    Range("D1:D" & UBound(Data, 2)) = WorksheetFunction.Transpose(WorksheetFunction.Index(Data, 4, 0))

End Sub

因此,我已将您更改sub_data为 2D 变体。结构与您预期的一样。

于 2013-09-17T08:05:41.367 回答