我一直试图弄清楚如何从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
为什么会发生这种情况,这种行为记录在哪里?
答案 0 :(得分: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 + 输入输入数组公式,而不仅仅是输入键。
答案 1 :(得分:1)
因为默认填充列而不是行。
试
=TRANSPOSE(Test())
如果你想填写行。
如果您想以编程方式更改默认值,也可以执行
Function Test()
.
.
.
Test = Worksheetfunction.Transpose(V)
End Function