• Class Module method (returns)

    Author
    Topic
    #466379

    Hello.
    I’m creating a class (in Excel 2003) to represent an employee.

    How can I create a method that returns a value? For example, I have a SalaryChange(value) method but I would like it to return
    the new salary.
    Is it possible to create a ‘hierarchy’ – that is a sub-class such as an Account? Thank you, Andy.

    Viewing 2 reply threads
    Author
    Replies
    • #1207891

      You could do it like this:

      Class clsEmployee

      Code:
      Option Explicit
      
      Private mdSalary As Double
      
      Public Function SalaryChange(dAddition As Double) As Double
          Salary = Salary + dAddition
          SalaryChange = Salary
      End Function
      
      Public Property Get Salary() As Double
          Salary = mdSalary
      End Property
      
      Public Property Let Salary(ByVal dSalary As Double)
          mdSalary = dSalary
      End Property
      

      In a normal module (or anywhere else you might use the employee class)

      Code:
      Option Explicit
      
      Sub Demo()
          Dim CEmployee As clsEmployee
          Set CEmployee = New clsEmployee
          With CEmployee
              .Salary = 100
              MsgBox "New salary equals: " & .SalaryChange(20)
          End With
      End Sub
      
    • #1207894

      Thank you very much.

      So a Public Sub is a method, but for a method to return a value it must be a Public Function? Is there any point in using Public Sub
      to represent a method, when I could use a function and just not return a value?

      My second question was – is it possible (with VBA) for a class to have another class as a member? Andy.

    • #1209417

      Equally valid question – is there any point in using a function and not returning a value? Makes no odds, really. 🙂
      And yes, you can simply declare a variable in one class as another class.

    Viewing 2 reply threads
    Reply To: Class Module method (returns)

    You can use BBCodes to format your content.
    Your account can't use all available BBCodes, they will be stripped before saving.

    Your information: