Consulting

Results 1 to 5 of 5

Thread: Listbox - calculation based on selections

  1. #1
    VBAX Regular
    Joined
    Sep 2016
    Posts
    17
    Location

    Listbox - calculation based on selections

    Hi All,

    I have a ListBox (lstBox1) on a userform that contains 12 items ("1" - "12")

    Each of these items is related to a TextBox on the form ("TextQty1" - "TextQty12")

    I am trying to get the sum of the corresponding values of "TextQty" selected from the ListBox items so that I can use this total in a sub elsewhere on the form. I am thinking something like:

    Total = 0
    If ListIndex0.Selected Then Total = Total + TextQty1.Value
    If ListIndex1.Selected Then Total = Total + TextQty2.Value


    But I really don't know how to structure this or if there is a better way, so can anyone please offer some advice?

    Thanks in advance,

    Anne

  2. #2
    VBAX Regular
    Joined
    Jan 2011
    Posts
    35
    Location
    Perhaps this:-
    Ensuring the Listbox Property is set at "Multiselect"
    Private Sub CommandButton1_Click()
    Dim Tot As Double, n As Long
    With ListBox1
        For n = 0 To .ListCount - 1
            If .Selected(n) Then
                Tot = Tot + Me.Controls("TextBox" & n + 1).Object.Value
            End If
        Next n
    End With
    MsgBox Tot
    End Sub
    Regards Mick

  3. #3
    Knowledge Base Approver VBAX Wizard
    Joined
    Apr 2012
    Posts
    5,645
    Private Sub UserForm_Click()
        For j = 0 To ListBox1.ListCount - 1
           y = y + ListBox1.List(j) * Abs(ListBox1.Selected(j))
        Next
        
        MsgBox y
    End Sub

  4. #4
    VBAX Regular
    Joined
    Sep 2016
    Posts
    17
    Location
    Hi Mick,

    That worked perfectly.

    Thank you for your help, it is greatly appreciated and has saved me hours of frustration.

    Regards,

    Anne

  5. #5
    VBAX Regular
    Joined
    Jan 2011
    Posts
    35
    Location
    You're welcome

Posting Permissions

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