spinjector
spinjector

Reputation: 3535

In a VBA class module, can a private instance variable be explicitly qualified as a public Enum from the same class..?

In a VBA custom class module (and by extension VB6?), if there's a private instance variable defined as a public enumeration from within the same class, should it be qualified..? If so, how..?

I often have project references with identical types. For instance, Excel and Word both have a Range object. As such, I'm always as specific as possible when declaring variables, such as Excel.Range or Word.Range, rather than just Dim R As Range.

But what about Enumerations..? How to be specific with these..? I've tried to qualify a variable as an enumeration, but I always get an error. I tried moving the enumeration definition to another custom class, but this didn't help. I don't often create classes for VBA, so I may be barking up the wrong tree with this.

If I qualify with the Me. keyword, I get the error:

"Compile error: Expected New or type name."

If I qualify with the custom class name, I get the error:

"Compile error: User-defined type not defined"

Here's a full example:

'Custom class module.
Option Explicit

Public Enum ImageAspect
    ImageAspectHorizontal
    ImageAspectVertical
End Enum

' Example 1:
' Qualified to use built-in Excel enumeration. This works.
Private logoAspect1 As Excel.XlOrientation 

' Example 2:
' Uses the enum defined in this class. This works, but...
' Can this be qualified..? How..? Is it even necessary?
Private logoAspect2 As ImageAspect

' Example 3:
' This does not work.
Private logoAspect3 As Me.ImageAspect

' Example 4:
' This does not work.
Private logoAspect4 As ThisClass.ImageAspect

Public Property Let Aspect(ByVal pAspect As ImageAspect)
    logoAspect2 = pAspect
End Property

Public Property Get Aspect() As ImageAspect
    Set Aspect = logoAspect2
End Property

Upvotes: 5

Views: 2198

Answers (1)

Erik A
Erik A

Reputation: 32672

They can only be classified at the project level.

Public types and enums are declared at the project level. This means they can't be classified further than the project, and you can't have multiple types or enums with the same name in a single project.

Public Enum ImageAspect
    ImageAspectHorizontal
    ImageAspectVertical
End Enum

Private logoAspect4 As VBAProject.ImageAspect

VBAProject is the default name of an Excel VBA Project. It can be renamed in the VBE under Tools -> VBAProject Properties

This is independent on if they're stored in a class module or normal module. They're always declared at the project level. If you want re-usable code across projects, you can store your enums and types in a different file with a distinct project name and reference that file to import the types and enums.

Upvotes: 1

Related Questions