[Webinar] Streamline your web hosting managementRegister Today

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 195
  • Last Modified:

Referencing List Box names with Variables

I have a form with 10 listboxes, lstDetails1...lstDetails10. I would like to fill each one with different dynamic data.

I could write 10 procedures to

1. open a database
2. select records
3. loop through and fill the list boxes

I would like to write a function and pass parameters including the listbox name to be filled along with the sql statement to get the data.

The sql part is easy but I cannot figure how to refernce a listbox from a variable.

this is what I want to do

function filllistbox(listboxname, sqlstring)

listboxname.additem "abcdef etc."
end loop

"listboxname" is a variable containing the name of the listbox.

Any ideas?

1 Solution
'A modular variable
dim ListBoxName as control

In the procedure you are calling the function from.
Set ListBoxName = lstDetails(1)

Now call your procedure to fill the listbox passing ListBoxName and the Sql Statement
This will work on combos and listboxes.  Lockwindowupdate keeps screen flicker to a minimum

Private Declare Function LockWindowUpdate Lib "user32" (ByVal hwndLock As Long) As Long

Public Sub PopulateList(obj As Object, db As Database, szSQL As String, Optional bIncludeAll As Boolean, Optional bPreserve As Boolean)
    Dim rs As Recordset
    Dim szVal As String
    Dim colSel As New Collection
    Dim nI     As Integer
    Dim bList  As Boolean
    Dim nJ     As Integer
    LockWindowUpdate obj.hwnd
    bList = StrComp(TypeName(obj), "LISTBOX", vbTextCompare) = 0
    If bList = 0 Then
        szVal = obj.Text
        For nI = 0 To obj.ListCount - 1
            If obj.Selected(nI) Then
                colSel.Add obj.List(nI)
            End If
        Next nI
    End If
    Set rs = db.OpenRecordset(szSQL, dbOpenForwardOnly)
    If bIncludeAll Then
        obj.AddItem "(All)"
    End If
    Do Until rs.EOF
        obj.AddItem rs.Fields(0) & vbNullString
        If rs.Fields.Count > 1 Then
            obj.ItemData(obj.NewIndex) = rs.Fields(1)
        End If
    Set rs = Nothing
    If bPreserve Then
        If bList Then
            For nJ = 1 To colSel.Count
                nI = SetList(obj, CStr(colSel.Item(nJ)))
                If nI > -1 And nI < obj.ListCount Then
                    obj.Selected(nI) = True
                End If
            Next nJ
            obj.ListIndex = SetList(obj, szVal)
        End If
    End If
    Set colSel = Nothing
    LockWindowUpdate 0
End Sub

Featured Post

Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now