Thu*_*ame 6 polymorphism vba interface class excel-vba
我有一个PublicNotCreatable接口PublicInterface
Option Explicit
Sub DoSomething()
End Sub
Run Code Online (Sandbox Code Playgroud)
而在同一工作簿中,我有一个片,Sheet1即器具 PublicInterface
Option Explicit
Implements PublicInterface
Private Sub PublicInterface_DoSomething()
Beep
End Sub
Run Code Online (Sandbox Code Playgroud)
然后,在Module1,我有代码,试图确定是否ThisWorkbook.ActiveSheet类型PublicInterface
Sub testSheet()
Dim sht As Object
For Each sht In ThisWorkbook.Sheets
'DOES run
Debug.Print "Enumerated Sheet Is PublicInterface"
Next sht
If TypeOf ThisWorkbook.ActiveSheet Is PublicInterface Then
'*** Doesn't run ***
Debug.Print "ThisWorkbook.ActiveSheet Is PublicInterface"
End If
Debug.Print ThisWorkbook.ActiveSheet.Name
If TypeOf ThisWorkbook.ActiveSheet Is PublicInterface Then
'DOES run
Debug.Print "After getting an ActiveSheet property, ThisWorkbook.ActiveSheet Is PublicInterface"
End If
If TypeOf ThisWorkbook.Sheets(ThisWorkbook.ActiveSheet.Name) Is PublicInterface Then
'DOES Run
Debug.Print "ThisWorkbook.Sheets(ThisWorkbook.ActiveSheet.Name) Is PublicInterface"
End If
If TypeOf ThisWorkbook.Worksheets(ThisWorkbook.ActiveSheet.Name) Is PublicInterface Then
'DOES Run
Debug.Print "ThisWorkbook.Worksheets(ThisWorkbook.ActiveSheet.Name) Is PublicInterface"
End If
'Force the project to reset
End
End Sub
Run Code Online (Sandbox Code Playgroud)
如果项目已被重置,似乎TypeOf ThisWorkbook.ActiveSheet Is PublicInterface返回False,但如果删除该End语句(因此项目未重置),并运行代码两次,则返回False第一次,True然后(直到项目重置),因为后续的代码行似乎强制解决了工作表的类型.同样,如果您单步执行代码,它True 每次都会返回.
有趣的是,TypeOf Sheet1 Is PublicInterface似乎工作.此外,在实现接口时,同样的问题并不明显ThisWorkbook,并且使用TypeOf ThisWorkbook Is PublicInterface确实返回True
这闻起来像VBA的bug.我怀疑它与工作表的编译时间有关.这是一个已知的问题?我在检查时做错了ThisWorkbook.ActiveSheet吗?我似乎无法重现与普通班是否这种行为Private还是PublicNotCreatable.
如果我需要检查工作簿的ActiveSheet是否实现了接口,这可能是最安全的方法:
If TypeOf ThisWorkbook.Sheets(ThisWorkbook.ActiveSheet.Name) Is PublicInterface Then