Is there a way to get the enums in VBA?

前端 未结 8 1956
南旧
南旧 2020-12-06 07:51

Is there a way to get the enums in VBA? Something like this example for C#, but for VBA?

using System;

class EnumsExampleZ
{
    private enum SiteNames
             


        
8条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-06 08:41

    Parsing the VBA code yourself with the VBIDE Extensibility library is going to appear nice & simple at first, and then you're going to hit edge cases and soon realize that you need to actually implement that part of the VBA spec in order to properly and successfully parse every possible way to define an enum in VBA.

    I'd go with the simple solution.

    That said Rubberduck is doing pretty much exactly that, and exposes an experimental COM API that allows you to enumerate all declarations (and their references) in the VBE, effectively empowering your VBA code with reflection-like capabilities; as of 2.0.11 (the latest release), the code would look something like this:

    Public Enum TestEnum
        Foo
        Bar
    End Enum
    
    Public Sub ListEnums()
        With New Rubberduck.ParserState
            .Initialize Application.VBE
            .Parse
            Dim item As Variant
            For Each item In .UserDeclarations
                Dim decl As Rubberduck.Declaration
                Set decl = item
                If decl.DeclarationType = DeclarationType_EnumerationMember Then
                    Debug.Print decl.ParentDeclaration.Name & "." & decl.Name
                End If
            Next
        End With
    End Sub
    

    And in theory would output this:

    TestEnum.Foo
    TestEnum.Bar
    

    However we (ok, I did) broke something around the 2.0.9 release, so if you try that in 2.0.11 you'll get a runtime error complaining about an invalid cast:

    broken experimental API

    That should be is an easy fix that we'll patch up by 2.0.12, but note that at that point the API is still experimental and very much subject to change (feature requests are welcome!), so I wouldn't recommend using it for anything other than toy projects.

提交回复
热议问题