VBA Code - Replacing Null Values with 0

backfromthebush

New Member
Joined
Jul 2, 2010
Messages
37
Hi all,

Im a struggling to come up with a custom function that replaces Null values in a table with Zero.

My table in its basic form has two fields....
Field A: Client
Field B: Quantity

The data is pulled from elsewhere in the database, but when it extracts it will have the client, and quantities... but some clients will have a Null quantity... e.g. below:

CLIENT QUANTITIES VALUE
Bob 9 9
Bill 16 16
Jane 0
Wendy 3 3
Mark 0
Andrew 11 11

I need the "Value" field to populate 0 if the Quantity = Null, otherwise populate with the Quantity value.

I thought the below code may work, but it keeps returning a #Error in the Value field. Any suggestions?? :biggrin:

PHP:
Function Value(Quantity As String) As Integer
If IsNull(Quantity) = True Then
    Value = 0
Else: Value = Quantity * 1
End If
End Function
 

Excel Facts

Lock one reference in a formula
Need 1 part of a formula to always point to the same range? use $ signs: $V$2:$Z$99 will always point to V2:Z99, even after copying
UDF isn't necessary. If you want to update the table directly, you can use an Update Query, i.e.
Code:
UPDATE MyTable SET MyTable.Value = 0
WHERE MyTable.Value Is Null;

If you just want to return it in a Query calculation, use the NZ function, which you tell it what to return in the event of a null value, i.e.
Code:
MyValue: NZ([Value],0)+0
We just add zero to the end to coerce it to return a number (the NZ function returns text by default, but adding a zero coerces it to a number).
 
Upvote 0

Forum statistics

Threads
1,224,522
Messages
6,179,297
Members
452,903
Latest member
Knuddeluff

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top