有没有办法使用单行为VBA中的数组赋值?

时间:2022-09-30 20:51:14

I am writing some excel-VBA, and I am assigning a number of integers (11 in total) to an array with index 1 to 11. Right now I am doing it one index at a time, and I was wondering if there is a way to do it in one line similar to how it is done in for example Matlab.

我正在写一些excel-VBA,我正在为一个索引为1到11的数组分配一些整数(总共11个)。现在我一次只做一个索引,我想知道是否有一个在一行中完成它的方式类似于在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 which is for me unwanted:

我知道可以在不将变量定义为数组的情况下完成,但是返回索引为0到10的数组,这对我来说是不需要的:

Dim cols As Variant

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

2 个解决方案

#1


4  

If a Variant array is OK:

如果Variant数组没问题:

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

#2


2  

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)

#1


4  

If a Variant array is OK:

如果Variant数组没问题:

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

#2


2  

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)