在 VBA 中从范围创建数组 [英] Creating an Array from a Range in VBA
问题描述
我遇到了一个看似基本的问题,但找不到任何资源来解决它.
I'm having a seemingly basic problem but can't find any resources addressing it.
简单地说,我只想将单元格范围(全部为一列)的内容加载到数组中.
Simply put, I just want to load the contents of a Range of cells (all one column) into an Array.
我可以通过
DirArray = Array(Range("A1"), Range("A2"))
但由于某种原因,我无法以这种方式表达数组:
But for some reason, I cannot create the array when expressed this way:
DirArray = Array(Range("A1:A2"))
我的实际范围要长得多(并且长度可能会有所不同),所以我不想以这种方式单独枚举单元格.谁能告诉我如何将整个范围正确加载到数组中?
My real Range is much longer (and may vary in length), so I don't want to have to individually enumerate the cells this way. Can anyone tell me how to properly load a whole Range into an Array?
后面的代码:
MsgBox UBound(DirArray, 1)
和
MsgBox UBound(DirArray)
返回 0,而前者返回 1.
Return 0, whereas with the former they return 1.
推荐答案
只需将变量定义为变体,并使它们相等:
Just define the variable as a variant, and make them equal:
Dim DirArray As Variant
DirArray = Range("a1:a5").Value
不需要数组命令.
这篇关于在 VBA 中从范围创建数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!