1

I thought that arrays were always passed by reference in VBA, but this example seems to be an exception:

' Class Module "C"

Private a_() As Long

Public Property Let a(a() As Long)
  Debug.Print VarPtr(a(0))
  a_ = a
End Property

' Standard Module

Sub test()

  Dim a() As Long: ReDim a(9)
  Debug.Print VarPtr(a(0))           ' output: 755115384

  Dim oc As C
  Set oc = New C
  oc.a = a                           ' output: 752875104 

End Sub

It's bugging me because I need to have a class containing an array and it's making an extra copy.

George Skelton
  • 1,095
  • 1
  • 10
  • 22
  • I have a similar question open [here](http://stackoverflow.com/questions/25328975/array-as-a-class-member) where, although it doesn't yet have an answer, the comments may be of use to you. – Blackhawk Sep 02 '14 at 17:02
  • Interesting problem, George, but what is the *question*? Are you looking to know *why*? Or are you looking for alternatives to creating three copies? – David Zemens Sep 02 '14 at 17:08
  • I'm looking for speed, although it's not a huge hit compared with populating the array in the first place. Ideally I would have liked `Public a_() as Long` to access the array directly from outside the class, but that's not possible. – George Skelton Sep 02 '14 at 17:31
  • I tried using an index interface to the array `Public Property Let a(index As Long, value As Long) : a_(index) = value : End Property` but that was substantially worse. – George Skelton Sep 02 '14 at 17:38
  • well I can see a way to *pass* the array by reference. Is that sufficient, or do you also need `OC.a_` to have the same memory pointer *after* it's been passed/assigned? – David Zemens Sep 02 '14 at 17:44
  • Let's see, how would you do that? – George Skelton Sep 02 '14 at 18:16
  • Sure thing, see below :) – David Zemens Sep 02 '14 at 18:38

1 Answers1

0

This seems to work, at least insofar as passing by reference:

Sub test()
Dim oc As New C
Dim a() As Long: ReDim a(9)

Debug.Print "test:    " & VarPtr(a(0))

oc.Set_A a()

End Sub

In class module C:

Private a_() As Long

Public Property Let a(a() As Long)
  Debug.Print "Let:    " & VarPtr(a(0))
  a_ = a
End Property

Function Set_A(a() As Long)
    Debug.Print "Set_A: " & VarPtr(a(0))
    a_ = a
End Function

I do note that the VarPtr evaluation of a(0) and oc.a_(0) is different, however, and I am not sure whether this is suitable for your needs:

enter image description here

David Zemens
  • 53,033
  • 11
  • 81
  • 130