我试图实现一个新类,该类正在Excel VBA中实现两个接口,但是我遇到了编译问题,因为接口的成员似乎在实现类中未正确实现(它们不可调用)。
接口如下:
ICrawlable
:
Option Explicit Public Function GetCrawler() As ICrawler End Function
IEquatable
:
Option Explicit Public Function Equals(CompareObject As Variant) As Boolean End Function
而ICrawlable
还拥有一个返回接口的函数ICrawler
:
Option Explicit Public Property Get CurrentItem() As Variant End Property Public Sub MoveNext() End Sub Public Function GetNext() As Variant End Function Public Function ItemsLeft() As Boolean End Function
我InterfaceTester
使用前两个接口创建了一个示例类:
Option Explicit Implements ICrawlable Implements IEquatable Private Function ICrawlable_GetCrawler() As Variant End Function Private Function IEquatable_Equals(CompareObject As Variant) As Boolean End Function
当尝试在模块中或其他任何地方使用该类时,我没有Intellisense支持。此外,该代码无法编译,并且在此模块代码中突出显示了“未找到方法或数据成员” .Equals
:
Sub TestInterfacing() Dim TestInstance As InterfaceTester Set TestInstance = New InterfaceTester Dim VerificationInstance As InterfaceTester Set VerificationInstance = New InterfaceTester Dim Result As Boolean Result = TestInstance.Equals(VerificationInstance) End Sub
这是VBA中的错误吗?我是否在接口中声明了不允许的内容(我已经尝试将所有返回数据类型更改为Variant并尝试禁用接口的每个功能)?我是否使用保留关键字(在对象资源管理器中,我看不到接口名称的重复项)?它可以在您的计算机上编译吗?
如果要使用接口中的方法,则必须将变量声明为以下接口类型:
Sub TestInterfacing() Dim TestInstance As IEquatable 'InterfaceTester Set TestInstance = New InterfaceTester Dim VerificationInstance As InterfaceTester Set VerificationInstance = New InterfaceTester Dim Result As Boolean Result = TestInstance.Equals(VerificationInstance) End Sub
但是,在这种情况下,您不能使用由此类实现的第二个接口中的方法ICrawlable
。
原因是在VBA中,实现方法如下所示:
Private Function ICrawlable_GetCrawler() As ICrawler
在使用其他语言的规则时,它应如下所示:
Public Function GetCrawler() As ICrawler
VBA无法理解这是接口方法的实现GetCrawler
。
为了解决此问题,您应该在InterfaceTester
class Equals
和中添加另外两个公共方法GetCrawler
。实现方法应仅针对那些方法:
InterfaceTester
类:
Implements ICrawlable Implements IEquatable Public Function Equals(CompareObject As Variant) As Boolean 'implementation End Function Public Function GetCrawler() As ICrawler 'implementation End Function Private Function ICrawlable_GetCrawler() As ICrawler Set IEquatable_Equals = GetCrawler End Function Private Function IEquatable_Equals(CompareObject As Variant) As Boolean IEquatable_Equals = Equals(CompareObject) End Function
现在,您可以将变量声明TestInstance
为InterfaceTester
类,并从两个接口使用方法。