Question on VB

  • Thread starter Thread starter mike
  • Start date Start date
M

mike

Hi all,

How do you pass a variable to a function and the function
returns something. I know this is a dump question, but I'm
new to VB.

Let says:

Dim a As Integer
Dim b As Integer
Dim c As integer

a=5
b=5
c=Sum(a,b) //This call the sum function and the funtion
returns the answer to c


Public Function Sum(first As Integer,second As Integer)

** What do I need to add here to return the total to c.
I'm placing this function in the Modules section in
access. **

End Function

Thnaks for the help.

mike
 
Mike,

The word "sum" is a Reserved Word in Access and Access does not like it if
Reserved Words are used for user-defined functions, Table Field Names, etc.,
so you should name your function something like SumIt.

Your function could read something like the following:

Function SumIt (first As Integer,second As Integer) as Integer

SumIt = first + second

End Function

Note that using Integer is somewhat limiting; if the sum of a+b returns a
value outside the range of -32,768 to 32,767 (the maximum field size for
Integer types), you will get an error. You may wish to work with Long
Integer.

Note also, you can sum variables without a function using VBA code as
follows:

Dim a as Integer
Dim b as Integer
Dim c as Integer

a = 5
b = 5
c = a + b

hth,
 
Try this:

function SumVals(a as integer, b as integer) as integer
'watch out for integer overflow

dim nRet as integer 'declare the sum variable
nRet = a + b 'do the calculation
SumVals = nRet 'pass the answer to the function name
end function

To use the function, just say
c = SumVals(a,b)

hth,
-M
 
Back
Top