我昨天以一个非常模糊的问题向你们咨询过。我现在设法隔离了这个问题,但显然没有像我在这里写的那样解决它。
对我来说,问题是为矩阵(或变体的变体)的值/内容分配变量。不确定这是否多余,但我希望在我的电子表格中有类似的内容:
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
答案 0 :(得分: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变体。结构与您预期的结构保持一致。