VBA Pass Array By Reference and Modify Contents

血红的双手。 提交于 2019-11-30 13:43:55

This is fairly trivial, using the ByRef keyword in the function signature will pass your array by reference rather than by value. This means that manipulations to that array will be preserved and bubble up to the calling scope. This is probably an oversimplification, but think of it this way:

  • ByRef: you're passing a reference to the thing (array, Object, etc.) and any transformations to that thing will be apparent anywhere that thing exists.
  • ByVal: you're passing the value representation of the thing. Essentially, you're passing a "copy" of it. You can manipulate this object, but it is not the same object from the calling scope, it's just a copy. So when the enclosing scope ends, you're still left with only the original thing.

Initialize your array as a numeric type and that will give you default 0 values.

Example as follows:

Option Explicit
Sub foo()
    Dim myArray(1 To 3) As Double  'The array is initialized with zero-values 

    Call bar(myArray)

    MsgBox myArray(3)

End Sub

Sub bar(ByRef dblArray() As Double)

    dblArray(1) = 123
    dblArray(2) = 345
    dblArray(3) = 33456

End Sub
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!