12

How do I implement my class ClsInterface, which has this code:

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

in my class Class2, which has this code:

Implements ClsInterface

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

My test code is

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

This always comes up with the following error:

Microsoft Visual Basic
Compile error:

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

but there is no help on Microsoft help (when I press on Help button).

Any Ideas?

Community
  • 1
  • 1
amr osama
  • 1,129
  • 2
  • 18
  • 34
  • 1
    Here's [How to use the Implements in Excel VBA](http://stackoverflow.com/questions/19373081/how-to-use-the-implements-in-excel-vba/19379641#19379641) –  May 01 '14 at 09:55

1 Answers1

15

Your Class2 must look like:

Implements ClsInterface

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

Check out the drop-down boxes at the top of Class2's code window, you can see what base object you can refer to; Class or ClsInterface.

In your test code you want:

Dim obj As New ClsInterface

If you want to call across the interface.

I would also recommend naming interfaces in the form ISomeDescription and using Dim then Set rather than Dim As New.

Alex K.
  • 171,639
  • 30
  • 264
  • 288
  • thank you, I followed your instructions it worked without any errors but the value is always 0 !!! while it should be 7, any idea? – amr osama Jul 03 '10 at 13:26
  • In your Private Function ClsInterface_add... you need 'Return x + y' instead of 'add = x + y', otherwise the value of x+y never gets returned. – Stewbob Jul 03 '10 at 17:53
  • 4
    You need to return using; ClsInterface_add = x + y – Alex K. Jul 04 '10 at 12:08
  • this isn't using an interface it's replacing class2 with clsinterface as class –  Oct 15 '13 at 08:02
  • 1
    I just looked for over an hour how to auto-implement a damn COM Interface in VB6 until I found your hint with the Drop-down boxes. Thanks for that. – Lennart Apr 22 '14 at 13:55