This is a matter of personal curiosity.
这是个人好奇心的问题。
In VBA, if I have an array of size 2:
在VBA中,如果我有一个大小为2的数组:
Dim r(1) as Variant
And I want both values in the array to be -1. I can do this:
我希望数组中的两个值都为-1。我可以做这个:
r(0)=-1
r(1)=-1
Or I could iterate through both with a loop and set them to -1.
或者我可以用循环迭代它们并将它们设置为-1。
So my question is, is there any way I can set all the values in an array to the same thing without iterating?
所以我的问题是,有没有什么方法可以将数组中的所有值设置为相同的东西而不进行迭代?
Or, is there any way I can do something like:
或者,有什么方法可以做我喜欢的事情:
r = array(-1,-1)
This might be a really stupid question but I can't seem to find the answer.
这可能是一个非常愚蠢的问题,但我似乎无法找到答案。
2 个解决方案
#1
5
Yes you can do it. But then you have to take care while declaring the array
是的,你可以做到。但是在声明数组时你必须小心
Example
例
Option Explicit
Sub Sample()
Dim r As Variant '<~~
r = Array(-1, -1)
Debug.Print r(0)
Debug.Print r(1)
End Sub
FOLLOWUP
跟进
See the Excel Help File :) The Array Function returns a Variant
containing an array
. You cannot assign an array to another array directly. To assign an array to another array you have to use this method.
请参阅Excel帮助文件:) Array函数返回包含数组的Variant。您无法直接将数组分配给另一个数组。要将数组分配给另一个数组,您必须使用此方法。
Option Explicit
Sub Sample()
Dim r(1) As Variant
Dim s As Variant
Dim i As Long
s = Array(-1, -1)
For i = LBound(r) To UBound(r)
r(i) = s(i)
Next
Debug.Print r(0)
Debug.Print r(1)
End Sub
#2
8
I'm not very good at drawing images. But this should give you and make clear the concepts associated with variant arrays.
我不是很擅长画画。但是这应该会给你并明确与变量数组相关的概念。
#1
5
Yes you can do it. But then you have to take care while declaring the array
是的,你可以做到。但是在声明数组时你必须小心
Example
例
Option Explicit
Sub Sample()
Dim r As Variant '<~~
r = Array(-1, -1)
Debug.Print r(0)
Debug.Print r(1)
End Sub
FOLLOWUP
跟进
See the Excel Help File :) The Array Function returns a Variant
containing an array
. You cannot assign an array to another array directly. To assign an array to another array you have to use this method.
请参阅Excel帮助文件:) Array函数返回包含数组的Variant。您无法直接将数组分配给另一个数组。要将数组分配给另一个数组,您必须使用此方法。
Option Explicit
Sub Sample()
Dim r(1) As Variant
Dim s As Variant
Dim i As Long
s = Array(-1, -1)
For i = LBound(r) To UBound(r)
r(i) = s(i)
Next
Debug.Print r(0)
Debug.Print r(1)
End Sub
#2
8
I'm not very good at drawing images. But this should give you and make clear the concepts associated with variant arrays.
我不是很擅长画画。但是这应该会给你并明确与变量数组相关的概念。