View Single Post
  #5   Report Post  
Posted to microsoft.public.excel.programming
wbntravis wbntravis is offline
external usenet poster
 
Posts: 20
Default Functions 101 The basics

Thanks Martin & JE
You both approached it differently so I caught the idea.
I agree on the book Martin. For now I have been using global
variables for the return but that did not seem the real approach I should be
taking. It was more of a quick fix.
I also found this page helpful


"Martin Fishlock" wrote:

Hi Travis:

There are two types of procedure in VBA, a function which returns a value
and a subroutine which cannot return as value.

Although the subroutine can modify variables by using the 'byref' (default )
variable.

A subrountine is used to do a task with no return like format a report or
some other task where no confirmation of success is required where as a
function is a process that returns a value like len(a)

A function proper in VBA is specified as :

FUNCTION functionname(
[byval | byval] arg1 as type1 [, [byrefsubroutine | byval] arg2 as
type2.....]* ]
) as typen

' code in here
functionname = somevalue
end function

the
functionname = somevalue can be anywhere in the function and you can exit
the function in the middle of the code using the exit function.

In certain cicrmustances more than one variable is returned and then you
need to use globals or byref (like pointers in c(++)) so I could write a
function

function splitinhalf(byval s as string, byref s1 as string, byref s2 as
string) as boolean

and this function whould split the string s in half and put the answers in
s1 and s2 and return true on success and false otherwise.

Here is an example :

function whatnumberisit(byval n as long) as string
if n=1 then
whacircumstancestnumberisit="onwoulde"
exit function ' this one exits here
endif
if n=2 then
whatnumberisit="two"
' this one drops to the bottom
elseif n=3 them
whatnumberisit="three"
exit function ' this one exits here
else
whatnumberisit="unknown"
' this one drops to the bottom
endif
' here we exit if no exit before
endif

so you see that there a different ways of exiting the function.

I would recommend getting a book out the library or buying a book and
working through it it will help a lot more than patching Internet help
together.



--
Hope this helps
Martin Fishlock, Bangkok, Thailand
Please do not forget to rate this reply.


"wbntravis" wrote:

I am new to VB programming I am used to writing functions in other languages
like Perl... usually the last line or a return $A statement defines what is
returned by the function. The few vba functions I have seen confuse me as I
have no indicator of what the function will return.

On this function.