在Excel 2016中返回一维数组
我一直在想如何从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
当我按ctrl+shift+enter
键入=Test()
到单元格的垂直范围内时,我得到预期的结果:
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
为什么会发生这种情况,这种行为logging在哪里?
首先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
然后在工作表中select三个垂直单元格和数组input :
=test()
数组公式必须使用Ctrl + Shift + Enterinput,而不仅仅是Enter键。
因为它默认填充列而不是行。
尝试
=TRANSPOSE(Test())
如果你想填写行。
如果你想改变默认的编程,你也可以做
Function Test() . . . Test = Worksheetfunction.Transpose(V) End Function