简体   繁体   中英

Is there a way to assign values to an Option Base 1 array in VBA using a single line?

I am assigning integers (11 in total) to an array with index 1 to 11, one index at a time.

Is there a way to do it in one line, similar to how it is done for example in Matlab.

How I am doing it now:

Dim cols(1 To 11) As Integer

cols(1) = 2
cols(2) = 3
cols(3) = 5
cols(4) = 6
cols(5) = 7
cols(6) = 9
cols(7) = 10
cols(8) = 13
cols(9) = 14
cols(10) = 15
cols(11) = 16

How I would like to do it:

Dim cols(1 To 11) As Integer

cols = [2,3,5,6,7,9,10,13,14,15,16]

I am aware that it can be done without defining the variable as an array, but that returns the array with index 0 to 10:

Dim cols As Variant

cols = Array(2,3,5,6,7,9,10,13,14,15,16]

If a Variant array is OK:

Dim cols()
cols = [{2,3,5,6,7,9,10,13,14,15,16}]

If you are okay with two lines instead of one line, you can try this:

Dim cols As Variant

cols = Array(2,3,5,6,7,9,10,13,14,15,16)
ReDim Preserve cols(1 To UBound(cols) + 1)

@Rory 有正确的答案,但我们可以让代码在视觉上看起来像是在这样的一行上:

Dim cols(): cols = [{2,3,5,6,7,9,10,13,14,15,16}]

Instead of repeating each number you can evaluate the row() function (if you aren't disposing yet of the SEQUENCE() function available in version 2019/365 *):

Dim cols: cols = Application.Transpose(Evaluate("row(2:16)"))
' cosmetic
ReDim Preserve cols(0 To UBound(cols) - 1)

Note: ReDim only if you want to get a zero based 1-dim array.

Hints to version MS Excel 365 *) the dynamic SEQUENCE() function can be applied immediately as formula on top of a vertical area, eg =SEQUENCE(15;1;2) ; integration into a VBA code to get a "flat" 1-dim array would result in

Dim cols: cols = Application.Transpose(Evaluate("SEQUENCE(15;1;2)"))

或者,如果您真的想要一行,请执行此操作

Dim cols(): cols = Array(2,3,5,6,7,9,10,13,14,15,16)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM