excelvbaclassmember-functions

VBA class member function and class definition problem continues


I send earlier question concerning class member function. Now I am facing a new problem, if the member function return value is a class where the function is defined.

The member function fReadData works ( I made an earlier question concering this ), the member function fReadData2 don't work.

Or: is the problem in test -functions ?

'ClassOne

Option Explicit

Private pOne As Double


Private Sub Class_Initialize()
    
End Sub


Private Sub Class_Terminate()
    
End Sub


Public Property Get One() As Double
    One = pOne
End Property


Public Property Let One(lOne As Double)
    pOne = lOne
End Property

' this works, return value is double
Public Function fReadData(alue As Range) As Double

    pOne = alue.Cells(1)
    fReadData = pOne
    
End Function

' this don't like to work, return value is ClassOne
Public Function fReadData2(alue As Range) As ClassOne

    pOne = alue.Cells(1)
    fReadData2.One = pOne
    
End Function

The test is as follows: both functions read a cell value and should put that on the spreadsheet

' main module

Option Explicit


Dim oOne As New ClassOne


' this works
Function Test(alue As Range) As Double

oOne.fReadData alue

Test = oOne.One

End Function


' this not
Function Test2(alue As Range) As Double

oOne.fReadData2 alue

Test2 = oOne.One

End Function

Test2 fails

Function Test2 should put the value of C1 to cell C3, like function Test did with cell B3


Solution

  • fReadData2.One = pOne
    

    fReadData2 is the reserved word inside the fReadData2 function to return the value from the function by the way of assigning it a value: fReadData2 = pOne. Thus, the member access operator (dot) can't be applied to it since the fReadData2 is empty (haven't any assigned value before).

    So, if you defined the fReadData2 function as ClassOne, you need to assign it the appropriate value, then you can assign values to public fields or properties:

      Set fReadData2 = New ClassOne
      fReadData2.One = pOne
    

    If you need to return the current object, use the Me identifier:

      pOne = alue.Cells(1)
      Set fReadData2 = Me