Home > Software design >  Why is my code printing only one ListBox value?
Why is my code printing only one ListBox value?

Time:10-05

My code is supposed to pull values from another sheet into a listbox, have the user select multiple items, and print those values to a new sheet. At the moment my code is only printing one value on the new sheet and isn't printing the full columns from the listbox, what am I doing wrong?

Private Sub CommandButton1_Click()
    Me.ListBox1.List = Worksheets("F8X SUSPENSION LINKS REV2").Range("B7:F22").Value
End Sub

Sub CompleteForm_Click()
    Dim x As Variant
    For x = 0 To Me.ListBox1.ListCount - 1
        If Me.ListBox1.Selected(x) Then

            ThisWorkbook.Worksheets("Part Order Form").Range("A2").Value = ListBox1.List(ListBox1.ListIndex)

        End If
    Next x

End Sub

CodePudding user response:

.Range("A2").Value value is being overwritten.

Private Sub CommandButton1_Click()
    Me.ListBox1.List = Worksheets("F8X SUSPENSION LINKS REV2").Range("B7:F22").Value
End Sub

Sub CompleteForm_Click()
    Dim PartCount As Long
    Dim x As Variant
    For x = 0 To Me.ListBox1.ListCount - 1
        If Me.ListBox1.Selected(x) Then
            
            ThisWorkbook.Worksheets("Part Order Form").Range("A2").Offset(PartCount).Value = ListBox1.List(ListBox1.ListIndex)
            PartCount = PartCount   1
        End If
    Next x

End Sub

CodePudding user response:

You need to loop over the list columns if you want all of the data from the selected items:

Sub CompleteForm_Click()
    Dim x As Long, i As Long, arr, arrSel, col As Long, ubRows As Long, ubCols As Long
    
    arr = Me.ListBox1.List                 'the full list
    ubRows = UBound(arr, 1)                'array upper bounds...
    ubCols = UBound(arr, 2)
    ReDim arrSel(0 To ubRows, 0 To ubCols) 'resize output array same as `arr`
    
    For x = 0 To ubRows                       'loop listbox items
        If Me.ListBox1.Selected(x) Then       'if item is selected
            For col = 0 To ubCols             'loop item columns
                arrSel(i, col) = arr(x, col)  'populate output array
            Next col
            i = i   1                         'next row in output array
        End If
    Next x
    
    If i > 0 Then 'any listbox items selected?
        'place the output array on the sheet
        ThisWorkbook.Worksheets("Part Order Form").Range("A2"). _
                     Resize(i, ubCols   1).Value = arrSel
    End If
End Sub

  • Related