How do I sum a list of numbers in a Visual Basic list box?

I need to sum (add up) a list of numbers in a list box in a Visual Basic program I am creating. Can anyone help me out with the necessary code?

Thanks in advance.

The following assumes that your listbox is populated with text strings that contain numbers… but that seems pretty obvious from your question. You need to use the ListCount property to determine how many items are in the control and then with a For…Next loop step throught the items, converting the contents to numbers with the Val function and adding them to a running total.

Assuming the listbox is named MyList:



    MyListSum = 0
    For n = 0 to MyList.ListCount - 1    ' index is zero based
         MyListSum = MyListSum + Val(MyList.Item(n))
    Next n


This example doesn’t include any error trapping for cases where the sum overflows, or to deal with cases where the contents of some of the items are non-numeric strings but for quick and dirty it will do the job

Hi loes motion,

Thanks for that, that’s great.

What about only wanting to sum one particular column (field) in a list box? Can that be done?

Cheers.

moes lotion.

Way to screw up the name of the person who is helping you :smack:

Out of curiosity, is this an access listbox? The standard VB listbox does not support multiple fields… or is this vb.net? (I tend to still think of visual basic as VB6, out of long practice.)

I don’t have a lot of time right now, but change the original Val(MyList.Item(n)) to something like Val(MyList.Column(n)). I think you need to specify a row as well, but maybe this can point you in the right direction in the help file.