vba 将数组中的所有值设置为相同内容的更好方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10704764/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 16:14:16  来源:igfitidea点击:

vba better way to set all values in array to same thing

vbaexcel-vbaexcel

提问by Alec

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.

这可能是一个非常愚蠢的问题,但我似乎无法找到答案。

采纳答案by Siddharth Rout

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 Variantcontaining 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 帮助文件 :) 数组函数返回一个Variant包含array. 您不能将一个数组直接分配给另一个数组。要将一个数组分配给另一个数组,您必须使用此方法。

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

回答by Pradeep Kumar

I'm not very good at drawing images. But this should give you and make clear the concepts associated with variant arrays.

我不太擅长画图。但这应该为您提供并明确与变体数组相关的概念。

variant versus variant array

变体与变体阵列