How to fill Listbox with data from another workbook (1 Viewer)

goncalo

Member
Local time
Today, 10:26
Joined
May 23, 2023
Messages
51
Hello everyone
I am writing here because im in need of help when it comes to putting information from another workbook on the list box

The code below works but what is really screwing me over is the way that the information is being sent to the list box
Code:
'----------------------------------------------------------List Box--------------------------------------------------------------------------
Sub UpdateListBoxAndSave()
    Dim sourceWorkbook As Workbook
    Dim sourceWorksheet As Worksheet
    Dim sourceRange As Range
    Dim listBox As MSForms.listBox 
    Dim dataArr As Variant
    Dim i As Long, j As Long
    Dim rowData As String

    Application.DisplayAlerts = False
    
   
    Set sourceWorkbook = Workbooks.Open("C:\Users\GCASTELO\Desktop\Teardown YF QR Code\dados.xlsm")
    Set sourceWorksheet = sourceWorkbook.Worksheets("Dados")

    Set sourceRange = sourceWorksheet.Range("B1:AA2")
    
 
    Set listBox = ThisWorkbook.Sheets("Sheet1").OLEObjects("ListBox1").Object
    
   
    listBox.Clear
    
  
    dataArr = sourceRange.value
    For i = 1 To 2 
        rowData = ""
        For j = 1 To UBound(dataArr, 2)
            Dim cellValue As String
            cellValue = Trim(dataArr(i, j))
            rowData = rowData & cellValue & vbTab
        Next j
        listBox.AddItem Trim(rowData) 
    Next i

    sourceWorkbook.Save
    sourceWorkbook.Close
    
    ' Re-enable display alerts
    Application.DisplayAlerts = True
End Sub


'-----------------------------------------------------------------------------------------------------------------------------------------------------------

In the image below you can see the values the listbox is being populated with
the main issue here is that the values from the second row are not under their respective columns (check the poorly drawn arrows to see where they should be)
Basically i need help to put the values from the second row right under their respective column

Capture.JPG

If anyone could help i would appreciate it,thanks for reading
 

cheekybuddha

AWF VIP
Local time
Today, 10:26
Joined
Jul 21, 2014
Messages
2,280
Why don't you use columns in your listbox rather than trying to space your values using vbTab (which I think is just 4 spaces) ?
 

goncalo

Member
Local time
Today, 10:26
Joined
May 23, 2023
Messages
51
Why don't you use columns in your listbox rather than trying to space your values using vbTab (which I think is just 4 spaces) ?
honestly didnt know there was a column property within the listboxes,its the first time i've used listboxes so i wasnt aware :/
ill give the thread a look and then say something if i managed to fix my issue!
 

Users who are viewing this thread

Top Bottom