Adam Gruszel
Adam Gruszel

Reputation: 21

Use function created in Class - VBA

I learn how work class. Please help me how to do something like this.

I prepared in Excel that Class:

Class name "Complex"

Option Explicit

Public Re As Double   'Real
Public Im As Double 'Imaginary

Public Function CCAdd(ParamArray Complex1() As Variant) as Complex
Dim i As Variant
Dim ZXC As Complex
Set ZXC = New Complex

For i = 0 To UBound(Complex1) 'Numer of arguments passed to the function
    If Not IsMissing(Complex1(i)) Then 'Omit arguments which don't exist
        If TypeName(Complex1(i)) = "Complex" Then ' Check is it Complex
            ZXC.Re = Complex1(i).Re + ZXC.Re
            ZXC.Im = Complex1(i).Im + ZXC.Im
        End If
    End If
Next i
Set Add = ZXC
Set ZXC = Nothing
End Function

In the Module I placed:

sub asd()
    Dim K As Complex
    Dim Z As Complex
    Dim A As Complex

    Set K = New Complex
    Set Z = New Complex
    Set A = New Complex

    K.Re = 1
    K.Im = 2

    Z.Re = 3
    Z.Im = 4

       A = K.CCAdd(K, Z)
end sub

After execute function CCAdd I get error with passing the value to "A". How solve this ? Maybe function can't pass non standard type of data.

Upvotes: 2

Views: 68

Answers (1)

Rory
Rory

Reputation: 34075

In the Complex class, this line:

Set Add = ZXC

needs to be:

Set CCAdd = ZXC

Then in the module, you just need:

Sub asd()
    Dim K As Complex
    Dim Z As Complex
    Dim A As Complex

    Set K = New Complex
    Set Z = New Complex

    K.Re = 1
    K.Im = 2

    Z.Re = 3
    Z.Im = 4

       Set A = K.CCAdd(K, Z)
End Sub

So you don't need to use Set A = New Complex but you do need to use Set when assigning it to the result of the CCAdd function.

Upvotes: 3

Related Questions