vbaexceluserformlistbox-control

How do I stop a loop from displaying the same String in a Multicolumn Userform Listbox?


I apologize if I do not get all the formalities correct but here goes nothing. I have a User-form that I have been developing and am getting stuck on how to get a list box (LB_JobItem) to populate based off a Combo-box selection (CB_JobSelect). So far I have gotten all fields to populate but they each display the same string, respectivley. When I select the Job Location This is what it out puts:

ListBox Output Image

This happens to be the last Value related to the location, (in this case Belleville), in the spreadsheet, See Data:

Data From Spread Sheet Image

What I'm trying to do is display unique Vendor, Item, and Unit Number Values within the list-box. It seems the the loop isn't going onto the next value with in the spreadsheet, and I don't know where its hanging in my code. Although I have a feeling it is with my "lastrow" declaration. Finally Attached is the code for the SUB:

    Private Sub CB_JobSelect_Change()

    Me.LB_JobItem.Clear


    Dim Vendor As String
    Dim Item As String
    Dim UnitNumber As String
    Dim CountJob As Integer
    Dim j As Integer
    Dim i As Integer
    Dim lastrow As Long


   Set ws = Sheets("PO_U_R")

   With Application.WorksheetFunction
   CountJob = .CountIf(ws.Range("G:G"), Me.CB_JobSelect.Value)
   End With

   lastrow = Sheets("PO_U_R").Range("A" & Rows.Count).End(xlUp).Row




   With Me.LB_JobItem



   For i = 1 To lastrow
      If ws.Cells(i, 7).Value = Me.CB_JobSelect.Value Then
      Vendor = ws.Cells(i, 5)
      End If
   Next i

   For i = 1 To lastrow
      If ws.Cells(i, 7).Value = Me.CB_JobSelect.Value Then
      Item = ws.Cells(i, 4)
      End If
  Next i

  For i = 1 To lastrow
      If ws.Cells(i, 7).Value = Me.CB_JobSelect.Value Then
      UnitNumber = ws.Cells(i, 2)
      End If
  Next i

  For j = 1 To CountJob

  .AddItem
  .List(j - 1, 0) = Vendor
  .List(j - 1, 1) = Item
  .List(j - 1, 2) = UnitNumber


  Next j
 End With

 End Sub

Solution

  • The issue is that you are assigning all the values first, then outputting the same value, N (CountJob) number of times.

    You need to output each as you find them, or use arrays.

    For i = 1 To lastrow
        If ws.Cells(i, 7).Value = Me.CB_JobSelect.Value Then
            .AddItem
            .List(.ListCount - 1, 0) = ws.Cells(i, 5)
            .List(.ListCount - 1, 1) = ws.Cells(i, 4)
            .List(.ListCount - 1, 2) = ws.Cells(i, 2)
        End If
    Next i