View Single Post
  #3   Report Post  
Posted to microsoft.public.excel.programming
Bob Phillips[_6_] Bob Phillips[_6_] is offline
external usenet poster
 
Posts: 11,272
Default Macro, Module, function, sub and This workbook and sheets ?

--

HTH

Bob Phillips
... looking out across Poole Harbour to the Purbecks
(remove nothere from the email address if mailing direct)

"Hari" wrote in message
...
Hi,

For the last couple of days I have been indiscriminately pinching codes

from
NG and pasting it in to This workbook or by inserting new modules without
understanding which should be used for what.


Careful, we'll have the copyright lawyers onto you<vbg

I am a newbie and want to learn VBA with excel.

Couple of questions based on this:-

1. What is the difference between Sub, Function, Module and code.


Subs and Functions are code procedures that will do something. A sub will
perform its actions, and exit quietly, whereas a Function will do it stuff,
but is usually used to return a result. For instance a sub is invoked like
this

runMySub
or
Call runMySub

whereas typically a function is called like this

myResult = runMyFunction

Just to confuse the matter, whilst a fuynction can return a result, it
doesn't have to, so it is possible just to use functions and never use subs.

A module is a con tainer within the VBE for holding the subs and functions,
and global variables, etc.

2. If I get a code ( from NG) where should I add it . Should I add it

"This
workbook" or a new module. If possible please tell me in what

circumstances
one should be adding the code in which of the above 2


That depends, workbook event code should go in the ThisWorkbook code module,
worksheet event code goes in the particular sheet code module, userform code
goes in the form class module, and most other code goes in a standard code
module. All can hold Subs or functions.

3. What is the difference between Public, private with reference to both

sub
and function.


A public sub/function can be invoked from another module, a private one
cannot.

4. When do we add codes to "Sheet1" rather than workbook.


Explained above.

5. Based on info from newsgroups I learned that a Macro/Module ( I believe
macro is recorded and module is anything which is written, please correct

me
if am wrong) could be called. Can we call both a macro and function from
another function/macro


Absolutely wrong. A macro is a generic term for a code procedure, that is a
sub or a function. When you record a macro it will defaul;t to a sub. As I
said above, a module is a container for subs and functions. A recorded macro
will also be assigned to a module.

You can call a sub or afunction from another sub or function, or even one
or more of both types.

6. Can a module in sheet call a module in another shet/workbook or from
module 1.


Modules can't call anything. See above.