Why would VBA TypeOf operator fail

后端 未结 3 1655
走了就别回头了
走了就别回头了 2021-01-08 00:34

I have been fighting with an Excel 2007 problem for several days now. Below is a listing of all facts I can think of that might be relevant:

  1. IDetailShee

相关标签:
3条回答
  • 2021-01-08 00:57

    I found this question after posting my own similar issue as TypeOf fails to work with Excel workbook's ActiveSheet that implements interface

    I don't have a definitive explanation, but I think I do have a workaround.

    I suspect it is because [the code] is implementing an interface on Sheet1 or Chart, and is extending Sheet1/Chart1, but Sheet1 is already extending Worksheet (and Chart1 is already extending Chart).

    In my testing, I am able to force VBA to return the real value of TypeOf by firstly accessing a property of the sheet. That means, doing something ugly like:

    'Explicitly access ThisWorkbook.ActiveSheet.Name before using TypeOf
    If TypeOf ThisWorkbook.Sheets(ThisWorkbook.ActiveSheet.Name) Is PublicInterface Then
    
    0 讨论(0)
  • 2021-01-08 01:07

    There are a few ways you could cheat using CallByName. You're going to have to work around this bug one way or another.

    A quick dirty example

    Every sheet that starts with an implementing line should have a public GetType function. I attached the "TestSheet" sub to a button on my ribbon. It puts the returned type name in cell A1 to demonstrate the function.

    Module1

    '--- Start Module1 ---
    Option Explicit
    
    Public Sub TestSheet()
      Dim obj As Object
      Set obj = ActiveSheet
      ActiveSheet.[A1] = GetType(obj)
    End Sub
    
    Public Function GetType(obj As Object) As String
      Dim returnValue As String
      returnValue = TypeName(obj)
      On Error Resume Next
      returnValue = CallByName(obj, "GetType", VbMethod)
      Err.Clear
      On Error GoTo 0
      GetType = returnValue
    End Function
    '--- End Module1 ---
    

    Sheet1

    '--- Start Sheet1 ---
    Implements Class1
    Option Explicit
    
    Public Function Class1_TestFunction()
    End Function
    
    Public Function GetType() As String
        GetType = "Class1"
    End Function
    '--- End Sheet1 ---
    
    0 讨论(0)
  • 2021-01-08 01:08

    If you're not trusting TypeOf, plough on and ignore errors:

    Dim sht as EXCEL.WorkSheet
    For Each sht in ActiveWorkbook.Worksheets
      'If TypeOf sht is IDetailSheet Then
      Dim DetailSheet As IDetailSheet
      On Error Resume Next
      Set DetailSheet = sht
      On Error GoTo 0
      If Not DetailSheet Is Nothing Then
        DetailSheets.Add DetailSheet, DetailSheet.Name
      End If
    Next sht
    

    If this doesn't work, the worksheets really aren't IDetailSheet at that time at least.

    0 讨论(0)
提交回复
热议问题