excel vba 如何通过引用数组名称来更改数组内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14694920/
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
excel vba how to change array content by referencing array name
提问by Max
I am trying to make change to the array named arraySrc in the following manner:
我正在尝试通过以下方式更改名为 arraySrc 的数组:
Dim arraySrc(0 To 1) As Integer
arraySrc(0) = 1
arraySrc(1) = 2
Dim arrayTmp
arrayTmp = arraySrc
arrayTmp(0) = 0
arrayTmp(1) = 1
Actually, I want to use one name as a handle to make change to multiple arrays individually by case, for example, I have a function to return the array name, I want to then set the returned array name to arrayTmp, then make change to arrayTmp directly using the format arrayTmp(0)=0 eg, hoping to make change to the original array
实际上,我想使用一个名称作为句柄来逐个更改多个数组,例如,我有一个返回数组名称的函数,我想将返回的数组名称设置为arrayTmp,然后更改为arrayTmp 直接使用格式arrayTmp(0)=0 eg,希望能对原数组做些改动
However, by using variant doesn't work. Can anybody please let me know how to implement this?
但是,通过使用变体不起作用。有人可以让我知道如何实施吗?
回答by bonCodigo
If you want to change values in arraySrc
you need to refer to the indices of that array.
如果要更改值,则arraySrc
需要参考该数组的索引。
e.g. which you have already done.
例如,您已经完成了。
arraySrc(0) = 1
arraySrc(1) = 2
Just because you copy arraySrc
to arrayTmp
, the latter is not going to keep the reference to arraySrc
.
仅仅因为您复制arraySrc
到arrayTmp
,后者不会保留对 的引用arraySrc
。
However this is possible if you had passed a reference of arraySrc
via a funtion's parameter.
但是,如果您arraySrc
通过函数的参数传递了 的引用,则这是可能的。
e.g.
例如
Option Explicit
Sub myArrays()
Dim arraySrc(0 To 1) As Integer
arraySrc(0) = 1
arraySrc(1) = 2
'-- the referencing
arrayReference arraySrc
End Sub
Function arrayReference(ByRef varr() As Integer) As Variant
If Not IsVarArrayEmpty(varr) Then
varr(0) = 0
varr(1) = 1
End If
arrayReference = varr
End Function
'--check for empty array - additional
Function IsVarArrayEmpty(anArray As Variant) As Boolean
Dim i As Integer
On Error Resume Next
i = UBound(anArray, 1)
If Err.Number = 0 Then
IsVarArrayEmpty = False
Else
IsVarArrayEmpty = True
End If
End Function
回答by Doug Glancy
Do you mean something like this? The ByRef argument means that the source array, passed as a parameter will also be changed:
你的意思是这样的吗?ByRef 参数意味着作为参数传递的源数组也将被更改:
Sub test()
Dim arraySrc(0 To 1) As Integer
arraySrc(0) = 1
arraySrc(1) = 2
PassByRef arraySrc
Debug.Print arraySrc(0)
Debug.Print arraySrc(1)
End Sub
Sub PassByRef(ByRef arrayTmp() As Integer)
arrayTmp(0) = 0
arrayTmp(1) = 1
End Sub