Results 1 to 16 of 16

Thread: [RESOLVED] Excel VBA - Populating A Multi-Column Listbox

  1. #1

    Thread Starter
    I'm about to be a PowerPoster! Hack's Avatar
    Join Date
    Aug 2001
    Location
    Searching for mendhak
    Posts
    58,333

    Resolved [RESOLVED] Excel VBA - Populating A Multi-Column Listbox

    For reasons I don't want to go into, I can't use a ListView for this. My only option is a multicolumn ListBox.

    I have one on a userform. It has 14 columns and I need to populate it based on a recordset created from a query against an Access database table.

    I have Googled this and found tons and zillions of examples of how to populate such an animal that is on a worksheet from data in cells on the worksheet but I didn't find anything on how to slap numerous rows of multicolumn data from a recordset.

    Also, is there a better way of creating column headers than using labels positioned above the listbox?

  2. #2
    Discovering Life Siddharth Rout's Avatar
    Join Date
    Feb 2005
    Location
    Mumbai, India
    Posts
    12,001

    Re: Excel VBA - Populating A Multi-Column Listbox

    Hack, Try this. Please amend the code as applicable.

    Code:
    '~~> Please set a reference to the Microsoft ActiveX Data Objects x.x Library!
    Option Explicit
    
    '~~> Database Name
    Const mdbPath = "C:\Hack.mdb"
    '~~> Connection String
    Const strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & mdbPath & ";"
    
    Dim cn      As New ADODB.Connection
    Dim rs      As New ADODB.Recordset
    Dim MyArray As Variant
    Dim sSQL    As String
        
    Private Sub CommandButton1_Click()
        sSQL = "SELECT * from Table1"
        
        cn.Open strCon
            
        '~~> Open recordset and copy to an array
        rs.Open sSQL, cn
        
        MyArray = rs.GetRows
        
        '~~> Update listbox
        With Me.ListBox1
            .Clear
            .ColumnCount = 5 '<~~ Column Count as Applicable
            .List = Application.Transpose(MyArray)
            .ListIndex = -1
        End With
        
        '~~> Close and cleanup
        rs.Close
        cn.Close
        Set rs = Nothing
        Set cn = Nothing
    End Sub
    Also, is there a better way of creating column headers than using labels positioned above the listbox?
    Not that I am aware of.

    Sid
    A good exercise for the Heart is to bend down and help another up...
    Please Mark your Thread "Resolved", if the query is solved


    MyGear:
    ★ CPU ★ Ryzen 5 5800X
    ★ GPU ★ NVIDIA GeForce RTX 3080 TI Founder Edition
    ★ RAM ★ G. Skill Trident Z RGB 32GB 3600MHz
    ★ MB ★ ASUS TUF GAMING X570 (WI-FI) ATX Gaming
    ★ Storage ★ SSD SB-ROCKET-1TB + SEAGATE 2TB Barracuda IHD
    ★ Cooling ★ NOCTUA NH-D15 CHROMAX BLACK 140mm + 10 of Noctua NF-F12 PWM
    ★ PSU ★ ANTEC HCG-1000-EXTREME 1000 Watt 80 Plus Gold Fully Modular PSU
    ★ Case ★ LIAN LI PC-O11 DYNAMIC XL ROG (BLACK) (G99.O11DXL-X)
    ★ Monitor ★ LG Ultragear 27" 240Hz Gaming Monitor
    ★ Keyboard ★ TVS Electronics Gold Keyboard
    ★ Mouse ★ Logitech G502 Hero

  3. #3

    Thread Starter
    I'm about to be a PowerPoster! Hack's Avatar
    Join Date
    Aug 2001
    Location
    Searching for mendhak
    Posts
    58,333

    Re: Excel VBA - Populating A Multi-Column Listbox

    Thanks Sid. I did kinda get it to work on my own, but it is real sloppy. I like your approach but I'm getting a type mismatch error on the highlight line.
    Code:
    Dim adoRS As ADODB.Recordset
    Dim sSQL As String
    Dim myArray As Variant
    sSQL = "My Query String here which works fine"
    Set adoRS = New ADODB.Recordset
    adoRS.Open sSQL, ADOCn  'ADOCn is my connection object created and executed elsewhere
    
    myArray = adoRS.GetRows
        
        '~~> Update listbox
        With Me.ListBox1
            .Clear
            .ColumnCount = 14 '<~~ Column Count as Applicable
            .List = Application.Transpose(myArray) 'Error 13 Type Mismatch here
            .ListIndex = -1
        End With
    
    adoRS.Close
    Set adoRS = Nothing

  4. #4
    Discovering Life Siddharth Rout's Avatar
    Join Date
    Feb 2005
    Location
    Mumbai, India
    Posts
    12,001

    Re: Excel VBA - Populating A Multi-Column Listbox

    Ah! that depends on the data. If you change that line to

    .List = myArray

    Does it populate the data? The orientation might be OFF though.

    Sid
    A good exercise for the Heart is to bend down and help another up...
    Please Mark your Thread "Resolved", if the query is solved


    MyGear:
    ★ CPU ★ Ryzen 5 5800X
    ★ GPU ★ NVIDIA GeForce RTX 3080 TI Founder Edition
    ★ RAM ★ G. Skill Trident Z RGB 32GB 3600MHz
    ★ MB ★ ASUS TUF GAMING X570 (WI-FI) ATX Gaming
    ★ Storage ★ SSD SB-ROCKET-1TB + SEAGATE 2TB Barracuda IHD
    ★ Cooling ★ NOCTUA NH-D15 CHROMAX BLACK 140mm + 10 of Noctua NF-F12 PWM
    ★ PSU ★ ANTEC HCG-1000-EXTREME 1000 Watt 80 Plus Gold Fully Modular PSU
    ★ Case ★ LIAN LI PC-O11 DYNAMIC XL ROG (BLACK) (G99.O11DXL-X)
    ★ Monitor ★ LG Ultragear 27" 240Hz Gaming Monitor
    ★ Keyboard ★ TVS Electronics Gold Keyboard
    ★ Mouse ★ Logitech G502 Hero

  5. #5
    Discovering Life Siddharth Rout's Avatar
    Join Date
    Feb 2005
    Location
    Mumbai, India
    Posts
    12,001

    Re: Excel VBA - Populating A Multi-Column Listbox

    The other way is to dimension the array and then fill the array from the rs in a loop and then simply use

    .List = myArray

    Sid
    A good exercise for the Heart is to bend down and help another up...
    Please Mark your Thread "Resolved", if the query is solved


    MyGear:
    ★ CPU ★ Ryzen 5 5800X
    ★ GPU ★ NVIDIA GeForce RTX 3080 TI Founder Edition
    ★ RAM ★ G. Skill Trident Z RGB 32GB 3600MHz
    ★ MB ★ ASUS TUF GAMING X570 (WI-FI) ATX Gaming
    ★ Storage ★ SSD SB-ROCKET-1TB + SEAGATE 2TB Barracuda IHD
    ★ Cooling ★ NOCTUA NH-D15 CHROMAX BLACK 140mm + 10 of Noctua NF-F12 PWM
    ★ PSU ★ ANTEC HCG-1000-EXTREME 1000 Watt 80 Plus Gold Fully Modular PSU
    ★ Case ★ LIAN LI PC-O11 DYNAMIC XL ROG (BLACK) (G99.O11DXL-X)
    ★ Monitor ★ LG Ultragear 27" 240Hz Gaming Monitor
    ★ Keyboard ★ TVS Electronics Gold Keyboard
    ★ Mouse ★ Logitech G502 Hero

  6. #6

    Thread Starter
    I'm about to be a PowerPoster! Hack's Avatar
    Join Date
    Aug 2001
    Location
    Searching for mendhak
    Posts
    58,333

    Re: Excel VBA - Populating A Multi-Column Listbox

    Well this is interesting.

    I changed the line of code to .List = myArray

    When I run a query that I know will bring back just one record, it puts all 14 items (0 through 13) into column 1

    When I run a query that I know will bring back multiple records, it populates the first three columns and then starts a new row and populates three columns and starts a new row and populates three columns etc.

    I have the columncount set to 14 in both the property page and in code.
    Attached Images Attached Images   

  7. #7

    Thread Starter
    I'm about to be a PowerPoster! Hack's Avatar
    Join Date
    Aug 2001
    Location
    Searching for mendhak
    Posts
    58,333

    Re: Excel VBA - Populating A Multi-Column Listbox

    On the other hand, this code does work for multiple records. The problem is it will only go to 9 columns.

    On column 10 I get an Error 380 “Could not set the List property. Invalid Property value.” Error
    Code:
    'query and other things are here
    Set adoRS = New ADODB.Recordset
    adoRS.Open sSQL, ADOCn
    Do While Not adoRS.EOF
    'myArray = adoRS.GetRows
        
        '~~> Update listbox
    '    With Me.ListBox1
    '        .Clear
    '        .ColumnCount = 14 '<~~ Column Count as Applicable
    '        .List = myArray
    '        '.List = Application.Transpose(myArray)
    '        .ListIndex = -1
    '    End With
    
       ListBox1.AddItem adoRS(0)
       ListBox1.List(i, 1) = adoRS(1)
       ListBox1.List(i, 2) = adoRS(2)
       ListBox1.List(i, 3) = adoRS(3)
       ListBox1.List(i, 4) = adoRS(4)
       ListBox1.List(i, 5) = adoRS(5)
       ListBox1.List(i, 6) = adoRS(6)
       ListBox1.List(i, 7) = adoRS(7)
       ListBox1.List(i, 8) = adoRS(8)
       ListBox1.List(i, 9) = adoRS(9)
    '   ListBox1.List(i, 10) = adoRS(10) 'this line gives me the 380 error
       i = i + 1
       adoRS.MoveNext
    Loop
    adoRS.Close
    Set adoRS = Nothing

  8. #8
    Discovering Life Siddharth Rout's Avatar
    Join Date
    Feb 2005
    Location
    Mumbai, India
    Posts
    12,001

    Re: Excel VBA - Populating A Multi-Column Listbox

    Yes, that is a limitation when you use .AddItem.

    See this link

    http://www.pcreview.co.uk/forums/xl-...-t2857402.html

    Did you try looping through the rs and then populating the multidimensional array as I suggested in #5? That ways you don't need to transpose and you will be able to use .List = myArray

    If you can upload a sample database then maybe I can show you an example?

    Sid
    Last edited by Siddharth Rout; Feb 22nd, 2011 at 02:56 PM.
    A good exercise for the Heart is to bend down and help another up...
    Please Mark your Thread "Resolved", if the query is solved


    MyGear:
    ★ CPU ★ Ryzen 5 5800X
    ★ GPU ★ NVIDIA GeForce RTX 3080 TI Founder Edition
    ★ RAM ★ G. Skill Trident Z RGB 32GB 3600MHz
    ★ MB ★ ASUS TUF GAMING X570 (WI-FI) ATX Gaming
    ★ Storage ★ SSD SB-ROCKET-1TB + SEAGATE 2TB Barracuda IHD
    ★ Cooling ★ NOCTUA NH-D15 CHROMAX BLACK 140mm + 10 of Noctua NF-F12 PWM
    ★ PSU ★ ANTEC HCG-1000-EXTREME 1000 Watt 80 Plus Gold Fully Modular PSU
    ★ Case ★ LIAN LI PC-O11 DYNAMIC XL ROG (BLACK) (G99.O11DXL-X)
    ★ Monitor ★ LG Ultragear 27" 240Hz Gaming Monitor
    ★ Keyboard ★ TVS Electronics Gold Keyboard
    ★ Mouse ★ Logitech G502 Hero

  9. #9

    Thread Starter
    I'm about to be a PowerPoster! Hack's Avatar
    Join Date
    Aug 2001
    Location
    Searching for mendhak
    Posts
    58,333

    Re: Excel VBA - Populating A Multi-Column Listbox

    Quote Originally Posted by koolsid View Post
    The other way is to dimension the array and then fill the array from the rs in a loop and then simply use
    Isn't that what myArray = rs.GetRows is doing?

  10. #10
    PowerPoster
    Join Date
    Dec 2004
    Posts
    25,618

    Re: Excel VBA - Populating A Multi-Column Listbox

    .List = Application.Transpose(myArray) 'Error 13 Type Mismatch here
    try
    .List = Application.worksheetfunction.Transpose(myArray)
    i do my best to test code works before i post it, but sometimes am unable to do so for some reason, and usually say so if this is the case.
    Note code snippets posted are just that and do not include error handling that is required in real world applications, but avoid On Error Resume Next

    dim all variables as required as often i have done so elsewhere in my code but only posted the relevant part

    come back and mark your original post as resolved if your problem is fixed
    pete

  11. #11
    Discovering Life Siddharth Rout's Avatar
    Join Date
    Feb 2005
    Location
    Mumbai, India
    Posts
    12,001

    Re: Excel VBA - Populating A Multi-Column Listbox

    Yes, but it is putting the values in vertical format (That is the reason we had to use transpose)

    If we hard code the array then it will be easier to use it with the listbox

    Edit
    If you can give me a sample database then I can give you an example.

    Sid
    Last edited by Siddharth Rout; Feb 23rd, 2011 at 06:23 PM.
    A good exercise for the Heart is to bend down and help another up...
    Please Mark your Thread "Resolved", if the query is solved


    MyGear:
    ★ CPU ★ Ryzen 5 5800X
    ★ GPU ★ NVIDIA GeForce RTX 3080 TI Founder Edition
    ★ RAM ★ G. Skill Trident Z RGB 32GB 3600MHz
    ★ MB ★ ASUS TUF GAMING X570 (WI-FI) ATX Gaming
    ★ Storage ★ SSD SB-ROCKET-1TB + SEAGATE 2TB Barracuda IHD
    ★ Cooling ★ NOCTUA NH-D15 CHROMAX BLACK 140mm + 10 of Noctua NF-F12 PWM
    ★ PSU ★ ANTEC HCG-1000-EXTREME 1000 Watt 80 Plus Gold Fully Modular PSU
    ★ Case ★ LIAN LI PC-O11 DYNAMIC XL ROG (BLACK) (G99.O11DXL-X)
    ★ Monitor ★ LG Ultragear 27" 240Hz Gaming Monitor
    ★ Keyboard ★ TVS Electronics Gold Keyboard
    ★ Mouse ★ Logitech G502 Hero

  12. #12
    Head Hunted anhn's Avatar
    Join Date
    Aug 2007
    Location
    Australia
    Posts
    3,669

    Re: Excel VBA - Populating A Multi-Column Listbox

    Try this (with header option in comments):
    vb Code:
    1. Private Sub CommandButton1_Click()
    2.     Const sDBPath = "D:\Documents\VBF\Sample.mdb"
    3.     Const sConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & sDBPath & ";"
    4.     Dim cn   As ADODB.Connection
    5.     Dim rs   As ADODB.Recordset
    6.     Dim sSQL As String
    7.     Dim i    As Long
    8.  
    9.     Set cn = New ADODB.Connection
    10.     Set rs = New ADODB.Recordset
    11.    
    12.     sSQL = "SELECT * FROM Plan"
    13.     cn.Open sConn
    14.     rs.Open sSQL, cn
    15.     With Me.ListBox1
    16.         .Clear
    17.         .ColumnHeads = False
    18.         If rs.EOF Then
    19.             .ColumnCount = 1
    20.             .AddItem "No record found"
    21.         Else
    22.             .ColumnCount = rs.Fields.Count
    23.             '-- use .Column to dump data,
    24.             '   don't use .List with Transpose() that also fails with single record
    25.             .Column = rs.GetRows()
    26.             '-- create fake column headers -----------
    27.             .AddItem , 0 '-- add header row
    28.             For i = 0 To rs.Fields.Count - 1
    29.                 .List(0, i) = rs.Fields(i).Name
    30.             Next
    31.             '-- To use sticky headers, recordset must be dumped to a sheet below a header row:
    32.             '   Sheet1.Range("A2").CopyFromRecordset rs
    33.             '-- then set:
    34.             '   .ColumnHeads = True
    35.             '   .Rowsource = "Sheet1!A2:S20" '--(exclude header row)
    36.             '-----------------------------------------
    37.             '-- set column widths as required:
    38.             .ColumnWidths = "40;50;30;30;30;30;30;30;30;30;30;30;30;30;30;30;30;30;30;30;30;30"
    39.             .TopIndex = 0 '-- scroll to top item
    40.         End If
    41.     End With
    42.     rs.Close: Set rs = Nothing
    43.     cn.Close: Set cn = Nothing
    44. End Sub
    • Don't forget to use [CODE]your code here[/CODE] when posting code
    • If your question was answered please use Thread Tools to mark your thread [RESOLVED]
    • Don't forget to RATE helpful posts

    • Baby Steps a guided tour
    • IsDigits() and IsNumber() functions • Wichmann-Hill Random() function • >> and << functions for VB • CopyFileByChunk

  13. #13

    Thread Starter
    I'm about to be a PowerPoster! Hack's Avatar
    Join Date
    Aug 2001
    Location
    Searching for mendhak
    Posts
    58,333

    Re: Excel VBA - Populating A Multi-Column Listbox

    This did it - all 14 columns
    Code:
        With Me.ListBox1
            .Clear
            .ColumnHeads = False
            .ColumnCount = adoRS.Fields.Count
            .ColumnWidths = "20;50;50;190;80;170;50;80;120;80;80;80;80;80"
            .Column = adoRS.GetRows
            .ListIndex = -1
        End With

  14. #14
    Discovering Life Siddharth Rout's Avatar
    Join Date
    Feb 2005
    Location
    Mumbai, India
    Posts
    12,001

    Re: [RESOLVED] Excel VBA - Populating A Multi-Column Listbox

    Thanks for the points Hack

    You finally made me create a sample database

    Here is what I was talking about...

    Code:
    Private Sub CommandButton1_Click()
        Const sDBPath = "C:\Hack.mdb"
        Const sConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & sDBPath & ";"
        Dim cn   As ADODB.Connection
        Dim rs   As ADODB.Recordset
        Dim sSQL As String
        Dim i    As Long
        Dim Myarray() As String
        
        Set cn = New ADODB.Connection
        Set rs = New ADODB.Recordset
        
        sSQL = "SELECT * FROM table1"
        cn.Open sConn
        rs.Open sSQL, cn, 1, 1
        With Me.ListBox1
            .Clear
            .ColumnHeads = False
            If rs.RecordCount < 1 Then
                .ColumnCount = 1
                .AddItem "No record found"
            Else
                .ColumnCount = rs.Fields.Count
                ReDim Myarray(rs.RecordCount, rs.Fields.Count)
                rw = 0
                Do While Not rs.EOF
                    For i = 1 To rs.Fields.Count - 1
                        If IsNull(rs.Fields(i)) Then Myarray(rw, i) = "" Else _
                        Myarray(rw, i) = rs.Fields(i)
                    Next
                    rw = rw + 1
                    rs.MoveNext
                Loop
                .List = Myarray
                .ColumnWidths = "50;50;50;50;50;50;50;50;50;50;50;50;50;50"
                .TopIndex = 0
            End If
        End With
        rs.Close: Set rs = Nothing
        cn.Close: Set cn = Nothing
    End Sub
    @Anhn: I liked the way you added Column Headers Hope you and your family are okay in nz. Feeling bad about CChurch.

    Sid
    A good exercise for the Heart is to bend down and help another up...
    Please Mark your Thread "Resolved", if the query is solved


    MyGear:
    ★ CPU ★ Ryzen 5 5800X
    ★ GPU ★ NVIDIA GeForce RTX 3080 TI Founder Edition
    ★ RAM ★ G. Skill Trident Z RGB 32GB 3600MHz
    ★ MB ★ ASUS TUF GAMING X570 (WI-FI) ATX Gaming
    ★ Storage ★ SSD SB-ROCKET-1TB + SEAGATE 2TB Barracuda IHD
    ★ Cooling ★ NOCTUA NH-D15 CHROMAX BLACK 140mm + 10 of Noctua NF-F12 PWM
    ★ PSU ★ ANTEC HCG-1000-EXTREME 1000 Watt 80 Plus Gold Fully Modular PSU
    ★ Case ★ LIAN LI PC-O11 DYNAMIC XL ROG (BLACK) (G99.O11DXL-X)
    ★ Monitor ★ LG Ultragear 27" 240Hz Gaming Monitor
    ★ Keyboard ★ TVS Electronics Gold Keyboard
    ★ Mouse ★ Logitech G502 Hero

  15. #15

    Thread Starter
    I'm about to be a PowerPoster! Hack's Avatar
    Join Date
    Aug 2001
    Location
    Searching for mendhak
    Posts
    58,333

    Re: [RESOLVED] Excel VBA - Populating A Multi-Column Listbox

    That works too.

    However, in the event some new person tries to run the code and it returns a compile error on an undefined variable, just add: Dim rw As Integer

  16. #16
    New Member
    Join Date
    Mar 2012
    Posts
    2

    Smile Re: [RESOLVED] Excel VBA - Populating A Multi-Column Listbox

    This was a great thread excel 2003 vba problems..populating a multicolumn listbox via ado and getting past the 10 .additem limitation !
    Everything in this thread I had the same errors !


    Thanks
    fordraiders

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