Is there a way to get the enums in VBA?

前端 未结 8 1871
南旧
南旧 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:30

    For above "John Coleman"'s example I suggest to use next functions:

    Function FruitType2Int(Fruit As FruitType)
        FruitType2Int = Format("0", Fruit)
        Debug.Print FruitType2Int
    End Function
    
    Function int2FruitString(i As Integer) As String
        If i = FruitType2Int(Orange) Then
            int2FruitString = "Orange"
        ElseIf i = FruitType2Int(Plum) Then
            int2FruitString = "Plum"
        ElseIf i = FruitType2Int(Apple) Then
            int2FruitString = "Apple"
        Else
            int2FruitString = "?"
        End If
        Debug.Print int2FruitString
    End Function
    

    Direct use of an Array indexes (without LBound() and etc.) may cause different resuts, depends on value in Option Base 1

    0 讨论(0)
  • 2020-12-06 08:36
    Public Enum col: [____]: cPath: cFile: cType: End Enum 
    Public Const colNames$ = "Path: cFile: cType"
    

    Not directly an answer and might look pretty ugly, but I thought it might be useful to others.
    In an old project I wanted to access columns with Enum (for example row(, col.cType) = 1).
    I changed the column location, name, use, etc. pretty often, but with this lazy approach I could just rearrange the Enum and then copy paste the change in the string constant, and get the table headers:

    Range("A1:C1").Value2 = Split(colNames, ": c")
    

    Names starting with _ are hidden by default, so [____] is used for padding and to avoid "cPath = 1"

    0 讨论(0)
  • 2020-12-06 08:38

    No - there is no native way to do this. You'd need to fully parse all of the user code and read the type libraries of any loaded projects and finally determine what scope each reference was referring to.

    Enumerations can't be treated like reference types in VBA, and this due to the deep roots that VBA has in COM. Enums in VBA are more like aliases, and in fact, VBA doesn't even enforce type safety for them (again, because of COM interop - MIDL specs require that they are treated as a DWORD).

    If you really need to do this in VBA, a good workaround would be to create your own enumeration class and use that instead.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-06 08:41

    If the reason you're looking for enum names is because you mean to use them in a user interface, know that even in C# that's bad practice; in .net you could use a [DisplayAttribute] to specify a UI-friendly display string, but even then, that's not localization-friendly.

    In excel-vba you can use Excel itself to remove data from your code, by entering it into a table, that can live in a hidden worksheet that can literally act as a resource file:

    localized captions

    Then you can have a utility function that gets you the caption, given an enum value:

    Public Enum SupportedLanguage
        Lang_EN = 2
        Lang_FR = 3
        Lang_DE = 4
    End Enum
    
    
    Public Function GetFruitTypeName(ByVal value As FruitType, Optional ByVal langId As SupportedLanguage = Lang_EN) As String
        Dim table As ListObject
        Set table = MyHiddenResourceSheet.ListObjects("FruitTypeNames")
        On Error Resume Next
        GetFruitTypeName = Application.WorksheetFunction.Vlookup(value, table.Range, langId, False)
        If Err.Number <> 0 Then GetFruitTypeName = "(unknown)"
        Err.Clear
        On Error GoTo 0
    End Function
    

    Or something like it. That way you keep code with code, and data with data. And you can quite easily extend it, too.

    0 讨论(0)
  • 2020-12-06 08:44

    There is no built-in function, though it is easy enough to roll your own in a concrete case:

    Enum FruitType
        Apple = 1
        Orange = 2
        Plum = 3
    End Enum
    
    Function EnumName(i As Long) As String
        EnumName = Array("Apple","Orange","Plum")(i-1)
    End Function
    

    If you have several different enums, you could add a parameter which is the string name of the enum and Select Case on it.

    Having said all this, it might possible to do something with scripting the VBA editor, though it is unlikely to be worth it (IMHO).

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