[AccessD] Function vs Sub (was: Classes and Events - EVENTS NOT REQUIRED)

Gustav Brock Gustav at cactus.dk
Tue Feb 24 11:46:10 CST 2009


Hi Charlotte

No, you are right, that is seldom. 
However, a sub may call(!) for more elegant code.

Instead of:

  curAmount = 12.345
  curAmount = RoundAmount(curAmount, 2)
  Debug.Print curAmount   ' Returns 12.35

then this:

  curAmount = 12.345
  Call RoundAmount(curAmount, 2)
  Debug.Print curAmount   ' Returns 12.35

or even:

  curAmount = 12.345
  RoundAmount curAmount, 2
  Debug.Print curAmount   ' Returns 12.35

Still a matter of taste, I guess.

/gustav

>>> cfoust at infostatsystems.com 24-02-2009 18:24 >>>
Absolutely when you need multiple return values, but a simple boolean or
single value?

Charlotte Foust 

-----Original Message-----
From: accessd-bounces at databaseadvisors.com 
[mailto:accessd-bounces at databaseadvisors.com] On Behalf Of Gustav Brock
Sent: Tuesday, February 24, 2009 1:45 AM
To: accessd at databaseadvisors.com 
Subject: Re: [AccessD] Function vs Sub (was: Classes and Events - EVENTS NOTREQUIRED)

Hi Charlotte

Not tidy? In some cases this feature is very useful. 
Here is a simple example of sub returning multiple values:

<code>
Public Sub CompositeRGB( _
  ByVal lngRGB As Long, _
  ByRef intRed As Integer, _
  ByRef intGreen As Integer, _
  ByRef intBlue As Integer)
  
' Calculate discrete RGB colours from composite colour Value.
'
' 1999-08-20. Cactus Data ApS, CPH
  
  If lngRGB < 0 Then
    ' Nothing to do.
    intRed = 0
    intGreen = 0
    intBlue = 0
  Else
    ' Dissolve composite RGB into discrete colours.
    intRed = lngRGB And vbRed
    intGreen = (lngRGB And vbGreen) / &H100
    intBlue = (lngRGB And vbBlue) / &H10000
  End If
  Debug.Print intRed, intGreen, intBlue
End Sub

</code>

The only reason I see to not write a sub when a return value is not
needed, is if the (sub)function will be used in a macro as these can't
call subfunctions.

/gustav


>>> cfoust at infostatsystems.com 24-02-2009 01:14 >>>
I didn't say functions HAD to return a value, just that you had to have
a function in order to return the value in this case.  Actually, using
ByRef for arguments passed into a sub allows you to get values back too,
but it isn't as tidy.

Charlotte Foust






More information about the AccessD mailing list