2016-01-22 57 views
2

我學習工作課程。請幫助我如何做這樣的事情。在課堂上使用創建的函數 - VBA

我在Excel中製備的類別:

類名稱 「複雜」

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 

在我放置在模塊:

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 

執行功能CCAdd後我得到誤差與通過所述值改爲「A」。如何解決此問題?也許函數不能傳遞非標準類型的數據。

回答

3

在Complex類,這條線:

Set Add = ZXC 

需求是:

Set CCAdd = ZXC 

然後在模塊中,你只需要:

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 

所以你不」 t需要使用Set A = New Complex,但在將其分配給的結果時,確實需要使用函數。