Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
185 views
in Technique[技术] by (71.8m points)

excel - 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.

I am able to accomplish this by means of

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?

With the latter code:

MsgBox UBound(DirArray, 1)

And

MsgBox UBound(DirArray)

Return 0, whereas with the former they return 1.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Just define the variable as a variant, and make them equal:

Dim DirArray As Variant
DirArray = Range("a1:a5").Value

No need for the Array command.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...