1

I am new and trying to understand VBA.

What is the different between modules and class modules? How come I can only have Macros inside Modules. (I think I am wrong here, but I don't know how to add a macro from Class modules)

In the end I'm having to add all my event handlers inside class modules and have all my macro code inside modules.

1

1 Answer 1

3

Modules are global through out the code. By default recorded Macros are saved in Modules, though you can cut the code and paste the Sub/Function into a class.

Mod1.DoSomething() ' Mod1 doesn't need to be instantiated, its global through the app, there is only one instance of it and that's called a Singleton pattern.

Classes are a concept where you need to instantiate them and their scope is limited.

Public globalScope as New Class0 ' <-- class0's methods are available in and outside a Module or Class.

Private memberScope as New Class1 ' <-- class1's methods are available inside the whole Module or Class.

Dim localScope as New Class2 ' <-- class2's methods are only available inside a Sub/Function.

You'll probably want to keep your event handlers in a Module as that's global. If you dispose a class with Events those events won't be available.

ps in .Net coding "Modules" are called Static Classes

Ps2 an fyi the difference between a Subroutine and a Function is; a Function returns a value where as a Subroutine just does something.

Sign up to request clarification or add additional context in comments.

4 Comments

Also note Forms are also a class module (with some form specific stuff) and work the same way. It is also an example of what to do with a class module.
Recorded "Macros" are never Functions. They are always Subs.
Typo: instane
Ps2: Generally correct. However a Function can be called as you would call a Sub. And Sub ByRef parameters are mutable and are all "returned".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.