1

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.

  • 3
    In that separate empty powerpoint file, did you put the type in a standard module as opposed to an object module? – GSerg Apr 23 '21 at 07:12
  • Does this answer your question? [User Defined Type (UDT) as parameter in public Sub in class module (VB6)](https://stackoverflow.com/questions/975982/user-defined-type-udt-as-parameter-in-public-sub-in-class-module-vb6) – Storax Apr 23 '21 at 07:32
  • Hi GSerg, it was a plain copy-paste to try and find the error. I could have used a class module by mistake. Thank you. – Jonh Smith Benjamin Apr 25 '21 at 08:17

1 Answers1

5

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)

FunThomas
  • 23,043
  • 3
  • 18
  • 34
  • Thanks for the reply. I think that was the error. I used a "class module" by accident instead of a "module". Object module = class module, right? – Jonh Smith Benjamin Apr 25 '21 at 08:22