View Single Post
  #6   Report Post  
Posted to microsoft.public.excel.programming
Bob Grossman Bob Grossman is offline
external usenet poster
 
Posts: 3
Default A simple function

Bob,

I was vaguely aware of some of this. My intent, once I was able to
see my function was to do something a lot more complicated starting
with declaring the data types to be integer.

I appreciate the help.

By the way, once I do get this function written - I will probably come
back to this group to ask how to make it available to all of the
worksheets written by my workgroup. I'll provide details on our
environment at that time.

Thanks again to all!

Bob.

On Fri, 29 Aug 2003 20:29:39 -0400, "Bob Kilmer"
wrote:

Some comments about variable types and type coercion:

Public Function func(range1, range2) 'As return type? (is Variant if
omitted)

Only the second of these will be a String
Dim r1, r2 As String
'the first will be Variant.
'Use Dim r1 As String, r2 As String to make both Strings.

'Assigning Doubles to String variables? Hmmm...
r1 = range1.Value
r2 = range2.Value

'Adding Strings?
func = r1 + r2

'Careful.
'VB will try to help by coercing variable types,
'but may concatenate strings instead of adding doubles.
func = CDbl(r1) + CDbl(r2)

End Function


Compare these:
Option Explicit

Public Function funcS(range1 As Range, range2 As Range) As String
Dim r1 As String, r2 As String
r1 = range1.Text
r2 = range2.Text
funcS = r1 + r2
End Function

Public Function funcD(range1 As Range, range2 As Range) As Double
Dim r1 As Double, r2 As Double
r1 = range1.Value
r2 = range2.Value
funcD = r1 + r2
End Function

Public Function funcD2(range1 As Range, range2 As Range) As Double
Dim r1 As String, r2 As String
r1 = range1.Value
r2 = range2.Value
funcD2 = r1 + r2
End Function

Public Function funcD3(range1 As Range, range2 As Range) As Double
funcD3 = range1.Value + range2.Value
End Function