Results 1 to 5 of 5

Thread: List boxes

  1. #1

    Thread Starter
    Fanatic Member joltremari's Avatar
    Join Date
    Sep 2000
    Location
    Mississippi
    Posts
    674

    Unhappy

    I am an EXTREME amateur in VB. I am working on a couple of small apps. trying to learn as I go. I was wondering how I can total (add up the values) of a column in a list box. The number of entries is user defined so during design I don't know how many will need totaling.
    Also when I add up anything by variables it strings them together: If No1 = 5 and No2 = 7, it gives me 57 instead of 12. None of the books I have tell me how to add using variables. Any help would be appreciated!

    [Edited by joltremari on 09-27-2000 at 04:23 PM]

  2. #2
    Guest
    Use Val() to convert the string to a number.
    Code:
    Private Sub Command1_Click()
    
        Dim Total As Long
        
        'Loop through the contents and add them
        For i = 0 To List1.ListCount - 1
            Total = Total + Val(List1.List(i))
        Next i
        
        MsgBox "The total is " & Total
            
    End Sub
    
    Private Sub Form_Load()
    
        'Populate the ListBox
        For i = 1 To 10
        List1.AddItem i
        Next i
        
    End Sub

  3. #3
    Addicted Member
    Join Date
    Jul 1999
    Location
    St-Élie d'Orford, Quebec, Canada
    Posts
    133
    Hi,

    the 57 -> 12 thing is because you are using strings or variants and you probably did "5" + "7" and what he did is "puts them together side by side". Sorry for the poor expression but I don't know how to say this in english...


    Do this :

    Result = cdbl(No1) + cdbl(No2)

    Watch out for string to number conversion errors...

    Here is a code exemple...

    BEGIN

    Dim i as long
    Dim lResult as long


    Listbox.ListIndex = 0
    lResult = 0

    For i = 0 to i = Listbox.ListCount-1

    lResult = lResult + CDbl(ListBox.Text)

    ListBox.Listindex = ListBox.Listindex + 1
    next


    END


    Or even better, use the itemdata property of the listbox to store your values : 1, 2, 3... and leave text in the text property... still with me here ?

    Hope I helped

  4. #4

    Thread Starter
    Fanatic Member joltremari's Avatar
    Join Date
    Sep 2000
    Location
    Mississippi
    Posts
    674
    That is what I needed to know. Thanks-a-gig Megatron

    [Edited by joltremari on 09-27-2000 at 05:39 PM]

  5. #5

    Thread Starter
    Fanatic Member joltremari's Avatar
    Join Date
    Sep 2000
    Location
    Mississippi
    Posts
    674
    Thats helps me tremendously, Thanks Vince!!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width