Jonh Smith Benjamin
Jonh Smith Benjamin

Reputation: 59

What is "Compile Error Cannot define a Public user-defined type within an object module"? : VBA

enter image description here

Compile error:

Cannot define a Public user-defined type within an object module

What does the above compile error mean in Visual Basic for Applications (VBA)?

I would like to point out that the exact same code had no error in a separate empty Powerpoint file.

Thank you.

Upvotes: 1

Views: 3126

Answers (1)

FunThomas
FunThomas

Reputation: 29466

You need to understand the different types of code modules in VBA. Basically, you can have

  • A regular module - here you put in code like subs, functions, types
  • A userform - I guess you know what a userform is. It contains the layout of the form and the so called code behind - that is all the code that is glued to the form, like event triggers.
  • A class module. A class is an own, user defined type. Additionally to a simple UDT (user defined type), a class has it's own functions and subroutines (yes, I know, this is extremely simplified)

Depending on the environment, you can have build-in modules. In Excel, these are Workbook and Worksheet modules, in Word the Document module (as far as I know in Powerpoint, there are no build in modules).

Now, all of the above, except for a regular module, define classes (user forms, worksheets, workbooks, documents are special kind of classes). And a class cannot contain a public type (it is already a public type), as simple as that. It's similar to the fact that you cannot define a Type within a Type.

I assume that you have your type defined in a user form code. If you need the type only within that form, declare it as private. It is allowed to define types within a class, but they need to be private, with other words, the type in unknown in other modules of your project, and, as a consequence, you cannot have public variables of that type or public functions that return that type.

If you need the type in more than one module, you need to move the type definition into a regular module (this is what GSerg wrote in the comments)

Upvotes: 6

Related Questions