tags:

views:

54

answers:

2

Hi,

I've got a question that probably has a pretty simple answer, but I didn't find a solution yet. Here's an example:

Public Function abc(var_1 As Variant) As Single
abc = 2 * var_1
End Function

I want to call that function in an Access query. Values for 'var_1' are from a numeric (single) data field. Problem: Some the values for var_1 are empty/missing. For those values I need the result of the function to be empty as well, but right now they are '0'.

I tried a lot of things already, but nothing works. The result for empty values is always '0' and not empty. Here's one try:

If IsNull(var_1) Then
        abc = Empty
        Exit Function
End If

Didn't work.

Any help for this problem would be very much appreciated. :)

Edit:

Thanks for the answers. I tried returning a variant before and it did return empty fields. However, the calculated field needs to behave as numberic and not as text, so this solution doesn't work for me. I ended up using the answer of Beth, though it's more work than I'd like to have. ;) Calling the function in SQL:

IIF(IsNull(X)=False;abc(X))

abc in VBA:

Public Function abc(var_1 As Single) As Single
abc = 2 * var_1
End Function
+1  A: 

Change the function to look something like the following.

Public Function abc(var_1 As Variant) As Variant
    If IsNumeric(var_1) Then
        abc = 2 * var_1
    Else
        abc = Null
    End If
End Function

I do not believe that you can return a null in a single as you were trying to do.

Buggabill
You might be causing some side effects with this code. Thanks to the wonder of Null Propagation 2*Null=Null. Therefore, you don't need to test for null to return null. However you aren't testing for null here you are testing for numeracy. So in the event of a non-numeric string value you get null instead of the usual error. This has the effect of suppressing errors that would lead to the detection (and possible recovery) of "dirty data". Really all you need to do is make sure you are using nullable types. I wouldn't bother with the IsNumeric test. Just my 2¢:) +1 for the nullable types though.
Oorang
So, would you just write it as `abc = 2 * var_1` and not worry about the test at all?
Buggabill
A: 

or test for null at a higher level than the function, although you'll have to do it everywhere the function is called

Beth
Sorry Beth, I just noticed that I can only accept one answer as the right one. I chose the one from Buggabill, because it's maybe more suited for others having the same problem.
donodarazao