有没有办法使用单行将值分配给 VBA 中的 Option Base 1 数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39509796/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a way to assign values to an Option Base 1 array in VBA using a single line?
提问by Johannes Veje
I am assigning integers (11 in total) to an array with index 1 to 11, one index at a time.
我将整数(总共 11 个)分配给一个索引为 1 到 11 的数组,一次一个索引。
Is there a way to do it in one line, similar to how it is done for example in Matlab.
有没有一种方法可以在一行中完成,类似于在 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:
我知道它可以在不将变量定义为数组的情况下完成,但是返回索引为 0 到 10 的数组:
Dim cols As Variant
cols = Array(2,3,5,6,7,9,10,13,14,15,16]
回答by Rory
If a Variant array is OK:
如果 Variant 数组没问题:
Dim cols()
cols = [{2,3,5,6,7,9,10,13,14,15,16}]
回答by SandPiper
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)
回答by Freelensia
@Rory has the right answer, but we can get the code to visually look like it's on one line like this:
@Rory 有正确的答案,但我们可以让代码在视觉上看起来像是在这样的一行上:
Dim cols(): cols = [{2,3,5,6,7,9,10,13,14,15,16}]
回答by T.M.
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 *):
您可以评估 row() 函数,而不是重复每个数字(如果您尚未处理SEQUENCE()版本 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.
注意:ReDim 仅当您想获得基于零的 1-dim 数组时。
Hints to version MS Excel 365*) the dynamic SEQUENCE()function can be applied immediately as formula on top of a vertical area, e.g. =SEQUENCE(15;1;2); integration into a VBA code to get a "flat" 1-dim array would result in
MS Excel 365 版本提示*) 动态SEQUENCE()函数可以作为公式立即应用于垂直区域的顶部,例如=SEQUENCE(15;1;2);集成到 VBA 代码中以获得“平面”一维数组将导致
Dim cols: cols = Application.Transpose(Evaluate("SEQUENCE(15;1;2)"))
Dim cols: cols = Application.Transpose(Evaluate("SEQUENCE(15;1;2)"))

