Adding values on a form

R

RMTechie

I'm trying to calculate total income and expenses from 5 fields each
on a form and then eventually calculate an income - expenses total.

I have the fields txtIncome1, txtIncome2, txtIncome3, txtIncome4,
txtIncome5 and txtExpense1, txtExpense2, txtExpense3, txtExpense4,
txtExpense5 as well as txtTotalIncome and txtTotalExpense

Originally, I just set the Control Source property of the
txtTotalIncome to add the values of my income fields, which worked as
long as there was data in all the fields. However, if one of my
fields was null, it would show up blank. Not sure how to fix this
without setting default values to 0, which I didn't really want to do,
as my form is clearer without all the 0's.

Instead, I set my "Current" event to the following code (which I
assume will need to be in my AfterUpdate field or something to update
as people add values) but I keep getting an "Object required" error
and can't figure out what I'm doing wrong.

Here is my code:

Private Sub Form_Current()
Dim varIncome As Long
Dim varIncome2 As Long
Dim varIncome3 As Long
Dim varIncome4 As Long
Dim varIncome5 As Long

Dim varExpense As Long
Dim varExpense2 As Long
Dim varExpense3 As Long
Dim varExpense4 As Long
Dim varExpense5 As Long

If txtIncome1 Is Null Then varIncome = 0 Else varIncome = txtIncome1
If txtIncome2 Is Null Then varIncome2 = 0 Else varIncome2 = txtIncome2
If txtIncome3 Is Null Then varIncome3 = 0 Else varIncome3 = txtIncome3
If txtIncome4 Is Null Then varIncome4 = 0 Else varIncome4 = txtIncome4
If txtIncome5 Is Null Then varIncome5 = 0 Else varIncome5 = txtIncome5

If txtExpense1 Is Null Then varExpense = 0 Else varExpense =
txtExpense1
If txtExpense2 Is Null Then varExpense2 = 0 Else varExpense2 =
txtExpense2
If txtExpense3 Is Null Then varExpense3 = 0 Else varExpense3 =
txtExpense3
If txtExpense4 Is Null Then varExpense4 = 0 Else varExpense4 =
txtExpense4
If txtExpense5 Is Null Then varExpense5 = 0 Else varExpense5 =
txtExpense5

txtTotalIncome = varIncome + varIncome2 + varIncome3 + varIncome4 +
varIncome5
txtTotalExpenses = varExpense + varExpense2 + varExpense3 +
varExpense4 + varExpense5

txtTotalAdjustedIncome = txtTotalIncome-txtTotalExpenses

End Sub

Please help! Thanks!
 
L

Linq Adams via AccessMonster.com

Use the Nz() function to convert Nulls to zeros in your formulas:

txtTotalIncome = Nz(varIncome, 0) + Nz(varIncome2, 0) + Nz(varIncome3, 0) +
Nz(varIncome4, 0) +Nz(varIncome5, 0)
 
L

Linq Adams via AccessMonster.com

BTW,

If txtExpense1 Is Null Then

doesn't work, because in Access VBA, the correct syntax would be

If IsNull(txtExpense1) Then

Notice that there is no space between IS and Null.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top