Sum a column of a listbox

I am trying to SUM a column in a list box and I’ve used the following and other iterations but none will give an answer other than zero. There are several examples of how to add rows but I cannot find code examples on how to add a row of numbers to provide a total. If someone could provide an example or provide a reference I would appreciate it. Many of the references that I have followed have turned out to be non-existent any longer so I ask for your help. Thank you.

Dim i as integer
Dim total as integer
For i=0 to PurchasesLB.ListCount-1
if PurchasesLB.Selected(i) then
total=total+Val(PurchasesLB.Cell(i, 4))

End if
Next

txtTotal.text = format(total, “###,###,##0.00”)

Your code will only add the selected rows, if no rows are selected then nothing will be added to total.

If you remove the ‘if’ then it should SUM all rows.

Note: it looks like you are using a regular Listbox and not a DesktopListbox (API 2)

1 Like

As @AlbertoD said, change these lines:

if PurchasesLB.Selected(i) then
total=total+Val(PurchasesLB.Cell(i, 4))

End if

to:

total=total+Val(PurchasesLB.Cell(i, 4))

Your previous code would only Sum any selected lines. Selected == highlighted, like this:

In the image, only ID 10 is selected, so the sum would be 75.

If no lines were selected the sum would be 0

If lines 3 and 4 were selected, the sum would be 123.

etc…

There’s not much wrong with your Code.

(API 2.0 Code)

Dim i As Integer
Dim total As Double // Val and CDbl deliver Doubles, so better use a Double
For i=0 To PurchasesLB.LastRowIndex
  // If PurchasesLB.RowSelectedAt(i) Then // Commented out, because only selected Rows would be added
  total=total+CDbl(PurchasesLB.CellTextAt(i, 4)) // Use CDbl instead of Val if you need to be international savy
  
  // End If
Next

txtTotal.Text = Format(total, "###,###,##0.00")

Thank you, AlbertoD, Anthony and Sascha for your guidance. The calculation now works. I appreciate your help.

3 Likes

if you have no input may put the original value in the celltag that there is no string convertion between.