PDA

View Full Version : VB Code Help: Sum Totaling a Textbox



FalconFlyer
04-19-2013, 04:54 PM
I appreciate anyone's help in advance. I am working on a survey form in Word 2007. I need to have the user check a checkbox (each checkbox is given a value of 5, 4, 3, 2, or 1) and the sum total of these checkboxes total in a textbox.

For Example, I checked one box (checkbox1 = 5) and one box for (checkbox2 = 4). I want the Textbox to read 9 (Adding the 2 values). It will currently display "54". I may have 4 or 5 checkboxes for each textbox (which I will need it to add all those boxes too).

My Code:

Private Sub CheckBox1_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles CheckBox1.CheckedChanged, CheckBox2.CheckedChanged
Dim textboxtext As String = String.Empty

If CheckBox1.Checked Then textboxtext += "5"
If CheckBox2.Checked Then textboxtext += "4"
TextBox1.Text = textboxtext
End Sub


Thank you.

fumei
04-19-2013, 09:10 PM
Umm, it appears you are asking for true VB, not VBA (String.Empty is not a VBA term). This is a VBA forum. Here is one way to do it in VBA.

Option Explicit

Private Sub CheckBox1_Change()
Call DoTheTextbox
End Sub

Private Sub CheckBox2_Change()
Call DoTheTextbox
End Sub

Private Sub CheckBox3_Change()
Call DoTheTextbox
End Sub

Private Sub CheckBox4_Change()
Call DoTheTextbox
End Sub

Private Sub CheckBox5_Change()
Call DoTheTextbox
End Sub

Sub DoTheTextbox()
Dim i As Long
If CheckBox1.Value = True Then i = i + 5
If CheckBox2.Value = True Then i = i + 4
If CheckBox3.Value = True Then i = i + 3
If CheckBox4.Value = True Then i = i + 2
If CheckBox5.Value = True Then i = i + 1
TextBox1.Text = i
End Sub

This way ALL of the checkboxes do the same thing, execute the Sub DoTheTextBox. Because the value of the textbox is calculated every time ANY change is made to ANY checkbox, it always reflects the current state of ALL of them. It works whether any given checkbox is being checked, or being unchecked. It is a change, and the textbox reflects the current state of all the checkboxes.

Caveat: You did not state what kind of checkboxes you are working with. The above works for legacy ActiveX checkboxes. It would be quite different for fomfields, and different again if you are talking about checkboxes on a userform (although that is strictly a naming issue).

FalconFlyer
04-20-2013, 07:33 AM
That is exactly what I needed. Thank you very much for your help.

I am a newbie to VB/VBA. I didn't realize there was a difference for the two. A friend asked if I could do this, and I thought it would be a good starter project/ challenge for me. Apparently too much so. Back to the books, I suppose. Thank you again.

fumei
04-20-2013, 12:23 PM
Oh, it is not so hard.