PDA

View Full Version : Creating a running total on a userform from one txtbox



Mediocre Egg
02-11-2008, 01:15 PM
I have something simple in mind but I can't figure out how to execute the idea. I looked on Google a bit and found things close to what I need but not close enough that I was able to come away with a solution. I am only a VBA hobbyist so this is probably very basic.

I have a userform with three controls: textbox (txtCost), button (cmdAdd), label (lblTotalCharge).

My goal is to have lblTotalCharge keep a running total of the amounts entered in txtCost and upon submitting the form, dump the total into a bookmark on my Word document.

The first thing I did was place this in Private Sub txtCost_Change():

lblTotalCharge.Caption = txtCost.Value

But once I have lblTotalCharge displaying the cost, I need a way to store it and add it to the next number entered into txtCost.

I figured the way to do this would be to set a variable equal to lblTotalCharge but I can't seem to get my head around what needs to come next.

Can anyone point me in the right direction?

Nelviticus
02-12-2008, 03:00 AM
The txtCost_Change event is probably the wrong place to put things as this runs every time the contents of the text box change, i.e. every time you press a key. I suspect you want to add to the total when the user clicks the Add button.

If I have that right then you could do something like this:
Option Explicit

Dim cTotal As Currency ' Our running total

Private Sub UserForm_Initialize()

' Set everything up
cTotal = 0
lblTotalCharge.Caption = cTotal
txtCost.Value = cTotal

End Sub

Private Sub cmdAdd_Click()

If IsNumeric(txtCost.Value) Then

' Add to the total and display it
cTotal = cTotal + Val(txtCost.Value)
lblTotalCharge.Caption = cTotal

End If

' Reset the cost box
txtCost.Value = 0
txtCost.SetFocus

End Sub

That way you're not using the label to store the running total, just display it. The value is actually stored in a variable.

If you set cmdAdd's 'default' property to 'true' this means that it gets 'clicked' whenever you hit the enter or return keys, so users can type a value in the text box, hit return, type another value and so on without reaching for the mouse.

Regards

Mediocre Egg
02-12-2008, 06:52 AM
That did the trick Nelviticus - thanks a lot! Plus I learned some new stuff like Val and IsNumeric.

fumei
02-12-2008, 11:28 AM
Nelviticus, very nicely done and well explained. Good one.