0

我一直在试图弄清楚如何从 VBA 函数返回数组。我遇到了这个网站:http ://www.cpearson.com/excel/returningarraysfromvba.aspx ,它提供了一些有用的例子,特别是这个:

Function Test() As Variant
    Dim V() As Variant
    Dim N As Long
    Dim R As Long
    Dim C As Long
    ReDim V(1 To 3, 1 To 4)
    For R = 1 To 3
        For C = 1 To 4
            N = N + 1
            V(R, C) = N
        Next C
    Next R
    Test = V
End Function

当我输入=Test()垂直范围的单元格时,ctrl+shift+enter我得到了预期的结果:

1
5
9

但是如果我想返回一个一维数组呢?我尝试修改函数以使 V 成为一维数组:

Function Test() As Variant
    Dim V() As Variant
    Dim N As Long
    Dim R As Long
    Dim C As Long
    ReDim V(1 To 3)
    For R = 1 To 3
        For C = 1 To 4
            N = N + 1
            V(R) = N
        Next C
    Next R
    Test = V
End Function

现在,当我将其输入相同的垂直范围时,我得到了:

4
4
4

为什么会发生这种情况,这种行为记录在哪里?

4

2 回答 2

3

首先TRANSPOSE()一维数组:

Function Test() As Variant
    Dim V() As Variant
    Dim N As Long
    Dim R As Long
    Dim C As Long
    ReDim V(1 To 3)

    For R = 1 To 3
        For C = 1 To 4
            N = N + 1
            V(R) = N
        Next C
    Next R
    Test = Application.Transpose(V)
End Function

然后在工作表中选择三个垂直单元格和数组输入

=test()

在此处输入图像描述


数组公式必须用Ctrl++Shift输入,Enter而不仅仅是Enter键。

于 2016-04-16T12:20:24.517 回答
1

因为它默认填充列而不是行。

尝试

=TRANSPOSE(Test())

如果你想填写行。

如果您想以编程方式更改默认值,您也可以这样做

Function Test()
    .
    .
    .
    Test = Worksheetfunction.Transpose(V)
End Function
于 2016-04-16T12:13:47.913 回答