VBA - Returning array from Property Get

后端 未结 3 1471
南旧
南旧 2020-12-05 11:22

If arrays are returned by reference, why doesn\'t the following work:

\'Class1 class module
Private v() As Double
Public Property Get Vec() As Double()
    V         


        
3条回答
  •  爱一瞬间的悲伤
    2020-12-05 11:53

    I want to suggest another nice way to do this using a Collection and a static Property without the need to use a class:

    imagine you want to have the xlCVError enum as an array (or collection), e.g. to loop through it on errors and handle it based on the actual error.

    The following is initialized once on access:

    'from https://stackoverflow.com/a/56646199/1915920
    Static Property Get XlCVErrorColl() As Collection
        Dim c As Collection  'will be already initalized after 1st access
                             'because of "Static Property" above!
        Set XlCVErrorColl = c
        If Not c Is Nothing Then Exit Property
    
       'initialize once:
    
        Set c = New Collection
        c.Add XlCVError.xlErrDiv0
        c.Add XlCVError.xlErrNA
        c.Add XlCVError.xlErrName
        c.Add XlCVError.xlErrNull
        c.Add XlCVError.xlErrNum
        c.Add XlCVError.xlErrRef
        c.Add XlCVError.xlErrValue
        Set XlCVErrorColl = c
    End Property
    

    Turning this into an array or implementing it as an array is straight forward, but collections seem to be more useful to me, with the disadvantage that their elements are not implicitely typed/(compile-time-)type checked.
    So this would e.g. turn it into an (read-only) array (with the in-mem-copy-disadvantage mentioned in other answers/comments):

    'from https://stackoverflow.com/a/56646199/1915920
    Static Property Get XlCVErrorArr() As XlCVError()
       Dim a() As XlCVError
       XlCVErrorArr = a
       If UBound( a ) > 0 Then Exit Property
    
       'initialize once:
    
       Dim c As Collection:  Set c = XlCVErrorColl
       ReDim a(c.Count)
       Dim i As Integer:  For i = 1 To c.Count 
           a(i) = c(i)
       Next i
       XlCVErrorArr = a
    End Function
    

    So transforming the example from Clayton Ss answer into a static, modifiable module property using some array it would be:

    'module (no class required)
    'from https://stackoverflow.com/a/56646199/1915920
    
    Private v() As Double
    
    Static Property Get Vec(index As Long) As Double
        If UBound(v) < 3 Then  'initialize once:
          ReDim v(0 To 3)  'one could initialize it with anyting after here too
        end if
    
        Vec = v(index)
    End Property
    
    Public Property Let Vec(index As Long, MyValue As Double)
        v(index) = MyValue
    End Property
    

提交回复
热议问题