Sub, module??

  • Thread starter Thread starter Francis Gaudreau
  • Start date Start date
F

Francis Gaudreau

Hi, I'm trying to learn VB within excel, and I'd like to
know what is the difference between a sub and a module, when to use
which
 
Subs are another name for VBA procedures, or macros. These are used to do
something specific.

A module is a container for code, and will contain subs and/or functions.
 
A Sub, like a Function, is a type of procedure, or executional unit of code.
Functions return a value in the sense that they can be used on the right of
an assignment statement or as a value in a statement:

Sub Main
Dim x as Long
Dim y as Long
Let x = 12

Let y = AtMost10(x)
Call Msgbox(Cstr(y))
'or just
Call Msgbox(AtMost10(x))

End Sub

Function AtMost10(x as Long) As Long
'limits x to 10
If x > 10 Then x = 10
'assign the return value to the fucntion name
AtMost10 = x
End Function

A Sub cannot return values in this way. This is the principal difference
between the two, although their arguments can be modified. Subs contain a
logical collection of steps in a process. By convention, a Sub named Main is
often the startup procedure for an entire program, though this is not
necessary in VBA.

A module is a collection of code, that will include one or more procedures
and/or variable declarations. In many languages, modules are stored as
separate files. Which procedures and variables go into which modules is to
some extent a matter of organizational preference, although some
limitations, requirements, and conventions apply.

Modules come in several forms: Standard, Class, Form, Sheet, Workbook,
others perhaps. Form, Sheet, Workbook, and others are specialized Class
modules. Standard modules can contain private or public Subs, Functions or
variables. Class modules are used to create a Class which is a potentially
complex software object. Unlike Standard modules, classes can include event
handlers, which are procedures (e.g., Sub Command1_Click) called by the
environment in response to some action that took place, like the mouse click
of a button or the tick of a clock.
 

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

Back
Top