PDA

View Full Version : [SOLVED:] Sum values vba code



Ryanchris
11-15-2019, 11:47 AM
Hello! I have a quote tool that I am developing with VBA. I need a place for users to add footages of pipe. I know that i can put a ton of textboxes on a sheet and then place a command button that would add add them all up but realistically, I would need a ton of those...

What I'd like for a user to do is be able to keep a running tally of numbers in a textbox and then be able to add those when ready. Text entered might look something like this (pretend the brackets represent the textbox...) [27, 48, 90, 122, 45, 67]. Any suggestions on how to do that? Please keep in mind that I am a rookie to VBA. Getting better but still figuring it out :)

Thank you in advance!!

Bob Phillips
11-15-2019, 12:15 PM
Why noy use the Excel grid?

Have the users add the, in column A say on a sheet, and have a cell that sums column A ad read that in your VBA.

Ryanchris
11-15-2019, 12:25 PM
It just wouldn't work with how we have the userforms set up

paulked
11-15-2019, 01:22 PM
Sub AddTxt()
Dim i As Long, l As Long, arr As Variant
arr = Split(Sheet1.TextBox1.Text, ",")
For i = 0 To UBound(arr)
l = l + Val(arr(i))
Next
MsgBox l
End Sub

Bob Phillips
11-15-2019, 02:30 PM
It just wouldn't work with how we have the userforms set up

Then change it, use the best tools for the job. That is what design is all about.

Ryanchris
11-15-2019, 06:36 PM
Paul - where do I apply this code? Do I need to create a command button (one that says "Calculate" for example and place the code with that?

SamT
11-15-2019, 08:15 PM
$User actions = Type in Textbox, press Enter, type in textbox, press Enter, Repeat as needed

In UserForm CodePage

Dim TextBox1Total As Double

Private Sub TextBox1_Enter()
TextBox1Total = 0
End Sub

Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
Cancel = True
TextBox1Total = TextBox1Total + CDbl(Me.TextBox1)
Me.TextBox1 = ""
MsgBox CStr(TextBox1Total)
End Sub

paulked
11-15-2019, 09:12 PM
@Ryanchris

Yes create a command button and if it's the first then



Private Sub CommandButton1_Click()
Dim i As Long, l As Long, arr As Variant
arr = Split(TextBox1.Text, ",")
For i = 0 To UBound(arr)
l = l + Val(arr(i))
Next
MsgBox l
End Sub

Change the red Textbox1 to whatever text box it is.

Or, As Sam suggests, you can do it on TextBox_Enter/Exit and have 'live' updates.

Ryanchris
11-15-2019, 10:44 PM
Yes!! Thank you all! Works brilliantly. Really appreciate all of your help - best wishes to everyone.

paulked
11-15-2019, 10:53 PM
You're welcome :thumb

SamT
11-16-2019, 12:22 AM
:cool: