如何从VBA函数返回一个长度不等的数组

我试图在一个更大的macros中写一个函数来返回一个元素列表。 该数组是从电子表格中的单元格生成的:

Function Elem_Array() As Variant Dim Elements() As Variant i = 1 Cells(i, 38).Select element1 = Cells(i, 38).Value element2 = "" Do While element2 <> element1 i = i + 1 Cells(i, 38).Select element2 = Cells(i, 38).Value ReDim Preserve Elements(1 To i) Elements(i) = element2 Loop Elements(1) = element1 Elem_Array= Elements End Function 

当试图设置Elem_Array等于Elements数组时,它将结束没有Elem_Array的任何函数。 当我调用函数时,我最终出现错误,因为我试图调用一个空的数组或string。 我已经尝试使用for循环一次填充Elem_Array一个元素,但函数结束时不添加任何内容。 元素()是变暗的变体或string不会改变任何东西。 对类似问题的build议涉及使用Elements()的集合,然后使用循环来使Elem_Array等于Elements,但是如果可能的话,我想尽量减less更改代码的次数。 任何帮助表示赞赏!

改变这个:

 Dim Elements() As Variant 

对此:

 Dim Elements As Variant 

第一条语句生成一组变体

你的函数返回types是“variablesvariables”(单数)而不是variables数组