Learning VBA-don't understand error message

B

beginner here

I’m starting to studying a new macro book that I just got, and in the current
section that I’m in, there is section that is called “Using user types with
arraysâ€. They have a sample code that I typed in a new spreadsheet, but when
I run the macro, I get this error

“cannot define a Public user-defined type within an object moduleâ€

My code that is causing the error is this, and I have checked several times
that I have typed the code in correctly.

“Type salesResults
spring As Single
summer AS Single
fall As Single
winter As Single
End Typeâ€

I have search the VBA help, to find out to try and correct this error, but
haven’t found anything that is close to answering it for me.

Can explain to me what I have done wrong.

Cal
 
C

Cal

Forgot to mention that this is being done in VBA version 6.5, and Excel
verison 2002.

Cal
 
D

Dave Peterson

You could have put the code under the ThisWorkbook module or under a
worksheet--or even in a class module.

You want to put that code in a General module:
With your workbook's project active:
Insert|Module
Is one way of getting there.
 
B

Bob Phillips

There is noting fundamentally wrong with that code.

It does need to be at the head of a module, before ant macros, and after
Option statements. Is that where you put it?
 
J

Jim Thomlinson

User defined tupes can only be placed in standard code modules. You can not
put them in worksheet modules, thisworkbook or in forms. That would be my
best guess as to what is happening...
 
T

Tim Zych

To add:

If this is in an object (class) module you could get it to work by making it
Private (Private Type salesResults), but then it's not directly accessible
outside that object. If you want to make the Type publicly available by any
code in the VBA project (Type salesResults or Public Type salesResults, same
thing), move it to a standard module, not a class module. Everything is a
class module in Excel except the one from Insert -> Module.

To read more in the help file, search for "Type Statement". However, I
believe the help file misstates the functionality a bit:

"In standard modules and class modules, user-defined types are public by
default. This visibility can be changed using the Private keyword."

Perhaps it would be helpful if it also noted, "Note that in Excel, a public
Type is allowable only in a standard module."
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top