2010-07-03 29 views
11

如何實現我的ClsInterface類,它有這樣的代碼:實現在VBA我自己的界面 - 錯誤:對象模塊需要實現「X」的界面「Y」

Public Function add(x As Integer, y As Integer) As Integer 
End Function 
Class2

,其中有這樣的代碼:

Implements ClsInterface 

Public Function add(x As Integer, y As Integer) As Integer 
add = x + y 
End Function 

我的測試代碼

Public Sub test() 
Dim obj As New Class2 
MsgBox obj.add(5, 2) 
End Sub 

這總是出現與以下錯誤:

Microsoft Visual Basic
Compile error:

Object module needs to implement 'add' for interface 'ClsInterface'
OK/Help

但沒有幫助的Microsoft幫助(當我按下幫助按鈕時)。

任何想法?

+1

這裏的[如何在Excel中使用VBA的器具(http://stackoverflow.com/questions/19373081/ how-to-use-the-implement -excel-vba/19379641#19379641) – 2014-05-01 09:55:07

回答

13

您的Class2必須看起來像;

Implements ClsInterface 

Private Function ClsInterface_add(x As Integer, y As Integer) As Integer 
add = x + y 
End Function 

(簽出下拉框在Class2中的代碼窗口的頂部,你可以看到你可以參考一下基本對象;類或ClsInterface)

在你希望你的測試代碼;

Dim obj As New ClsInterface 

如果您想通過接口進行呼叫。

(我也建議形式ISomeDescription命名intefaces和使用設置,而不是作爲新)

+0

謝謝你,我遵循你的指示,它的工作沒有任何錯誤,但價值永遠是0!而它應該是7,任何想法? – 2010-07-03 13:26:38

+0

在你的私人函數ClsInterface_add ...你需要'返回x + y'而不是'add = x + y',否則x + y的值永遠不會返回。 – Stewbob 2010-07-03 17:53:32

+4

您需要返回使用; ClsInterface_add = x + y – 2010-07-04 12:08:20